14、实现ajax请求
通过 JavaScript 的 异步通信,从服务器获取 XML 文档从中提取数据,再更新当前网页的对应部分,而不用刷新整个网页。
步骤:
- 创建一个 XMLHttpRequest 对象。
- 设置超时时间。
- 定义成功和失败的回调函数。
- 监听请求状态变化,并在请求完成时检查 HTTP 状态码,调用相应的回调函数。
- 处理网络错误和超时错误。
- 打开请求,设置请求头和响应类型,并发送请求。
代码:
const SERVER_URL = "test.json"
// 创建请求
const xhr = new XMLHttpRequest();
// 设置超时时间
const timeout = 1000;
// 成功的回调函数
function onSuccess(res){
console.log("Success:" , res)
}
// 失败的回调函数
function onError(res){
console.log("Error:" , res)
}
// 监听状态:包括ajax的和http的
xhr.onreadystatechange = () => {
if (xhr.readyState !== 4) return;
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
onSuccess(xhr.response);
}else {
onError(xhr.response)
}
};
// 错误的情况
xhr.onerror = function() {
onError("错啦"+xhr.response);
};2
// 超时的情况
xhr.ontimeout = function(){
onError("超时啦"+xhr.response);
}
// 先open
xhr.open("GET", SERVER_URL, true);
// 设置请求头
xhr.setRequestHeader("Accept", "application/json");
// 设置请求类型
xhr.responseType = "json";
// 发送请求
xhr.send(null);
`