
Ajax
1.创建 XMLHttpRequest对象

XML
2.设置请求参数
xhr.open('GET', 'url');
xhr.setRequestHeader('Content-Type', 'application/JSon');
3.发送请求
xhr.send();
4.响应处理
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
}
5.错误处理
xhr.onerror = function () {
console.log('请求出错!');
}
示例:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data.JSon', true);
xhr.setRequestHeader('Content-Type', 'application/JSon');
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
}
xhr.onerror = function () {
console.log('请求出错!');
}
Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号