原生JS实现Ajax请求
第一步: 获得XMLHttpRequest对象
var ajax = new XMLHttpRequest();
第二步: 设置状态监听函数
ajax.onreadystatechange = function(){
console.log(ajax.readyState);
console.log(ajax.status);
第五步:在监听函数中,判断readyState=4 && status=200表示请求成功
if(ajax.readyState==4 && ajax.status==200){
第六步: 使用responseText、responseXML接受响应数据,并使用原生JS操作DOM进行显示
console.log(ajax.responseText);
console.log(ajax.responseXML); // 返回不是XML,显示null
console.log(JSON.parse(ajax.responseText));
console.log(eval("("+ajax.responseText+")"));
}
}
第三步: open一个链接
ajax.open("GET","h51701.json",false); //true异步请求,false同步
第四步: send发送一个请求。 可以发送对象和字符串,不需要传递数据发送null
ajax.send(null);
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function(){
console.log(ajax.readyState);
console.log(ajax.status);
if(ajax.readyState==4 && ajax.status==200){
console.log(ajax.responseText);
console.log(ajax.responseXML);// 返回不是XML,显示null
console.log(JSON.parse(ajax.responseText));
console.log(eval("("+ajax.responseText+")"));
}
}
ajax.open("GET","h51701.json",false);//true异步请求,false同步
ajax.send(null);