function requestJSON1() {
try {
// 1.异步请求对象构建
let xhr = new XMLHttpRequest()
// 2.设置异步请求参数
xhr.open("get", "http://127.0.0.1:3000/public/json")
// let obj = null
// console.log(obj.name);
// readyState 属性是描述当前ajax请求的执行步骤
// 0 异步对象未创建
// 1 异步对象已完成配置
// 2 异步请求已发送,尚未接收到服务器响应
// 3 服务器响应已到达,开始接收响应数据
// 4 响应数据接收完成,异步请求结束
// ajax 步骤状态发生变化是执行的方法
// xhr.onreadystatechange = function(){
// // 监控状态变化的
// console.log( xhr.readyState );
// if(xhr.readyState==4){
// }
// }
// 当ajax 请求成功后执行的方法
xhr.onload = function () {
// http code 响应状态码
console.log(xhr.status);
if (xhr.status < 400) {
alert("请求成功")
document.querySelector("#user").innerHTML = xhr.responseText
} else if (xhr.status < 500) {
alert("资源错误")
} else {
alert("服务器错误")
}
}
// 2.1 定义监控函数
// 监控网络错误 net work error
xhr.onerror = function (error) {
console.log(error);
console.log(error.type);
alert("网络连接中断")
}
// 3.请求发送
// + JS代码错误
// + 网络通信错误
// + 服务器拒绝或运行错误
xhr.send()
} catch (error) {
console.error(error);
alert("程序运行错误,请求联系管理员")
}
}
JS原生异步请求
于 2022-08-27 15:06:35 首次发布