xmlhttprequest怎么发送请求
XMLHttpRequest是一种用于向服务器发送HTTP请求的JavaScript API。要使用XMLHttpRequest发送请求,可以按照以下步骤:
- 创建一个XMLHttpRequest对象:
var xhr = new XMLHttpRequest();
- 设置请求的方法、URL以及是否异步:
xhr.open('GET', 'http://example.com/api/data', true);
- 设置请求头部:
xhr.setRequestHeader('Content-Type', 'application/json');
- 设置请求完成后的回调函数:
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Request failed: ' + xhr.status);
}
}
};
- 发送请求:
xhr.send();
上述代码将向http://example.com/api/data发送一个GET请求,并在请求完成后将响应输出到控制台中。如果请求失败,则在控制台中打印错误消息。
原文地址: http://www.cveoy.top/t/topic/LOa 著作权归作者所有。请勿转载和采集!