Использовать XMLHttpRequest .
Простой запрос GET
httpRequest = new XMLHttpRequest()
httpRequest.open('GET', 'http://www.example.org/some.file')
httpRequest.send()
Простой запрос POST
httpRequest = new XMLHttpRequest()
httpRequest.open('POST', 'http://www.example.org/some/endpoint')
httpRequest.send('some data')
Мы можем указать, что запрос должен быть асинхронным (true), по умолчанию или синхронным (false) с необязательным третьим аргументом.
// Make a synchronous GET request
httpRequest.open('GET', 'http://www.example.org/some.file', false)
Мы можем установить заголовки перед вызовом httpRequest.send()
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Мы можем обработать ответ, установив httpRequest.onreadystatechange
в функцию перед вызовом httpRequest.send()
httpRequest.onreadystatechange = function(){
// Process the server response here.
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}