JavaScript能够通过XMLHttpRequest对象向服务器发送HTTP请求。XMLHttpRequest对象是AJAX编程的核心,可以在不刷新页面的情况下从服务器获取数据。
下面是一个简单的示例代码,向服务器发送一个GET请求并处理返回的数据:
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('请求失败。');
}
};
xhr.send();
使用XMLHttpRequest对象发送HTTP请求时,需要设置请求的方法(GET或POST)、请求的URL、请求是否异步处理(true或false)等参数。同时可以设置请求头、请求体等其他参数。
下面是一个使用POST方法向服务器发送数据的示例代码:
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://api.example.com/data');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('请求失败。');
}
};
const data = {name: 'John', age: 30};
xhr.send(JSON.stringify(data));
此示例代码中设置请求头为application/json,并将数据以JSON格式发送到服务器。