<script>
/*
ajax的兼容
==>ajax不主动向下兼容
==>ajax的兼容有两个部分
1、创建ajax对象
2、接收响应
创建ajax对象的兼容
1、new XMLHttpRequest() 标准浏览器使用
2、new ActiveXObject('Msxml.XMLHTTP') IE7 8 9
3、new ActiveXObject('Msxml2.XMLHTTP') IE6
4、new ActiveXObject('Microstft.XMLHTTP') IE5.5+
5、再往下的IE不支持ajax
=>如果用的是IE 11 浏览器,跑不起来
->ajax是基于内核的兼容
接收响应兼容
==>在低版本IE里面没有onload事件
==>只能使用onreadystatechange事件来接收响应
=>在事件里面进行判断
=>xhr.status在200-299之间
=>xhr.ready===4的时候
=>正常使用响应体
ajax状态码
==>响应状态码:描述本次请求的状态
==>ajax状态码:描述ajax进行到哪一个步骤了
语法:xhr.readyState
0:创建ajax对象成功
1:配置请求信息完成
2:请求发送出去了,响应报文回到了浏览器
3:浏览器正在解析响应报文
4:浏览器解析响应报文成功,已经可以正常使用xhr.responseText
ajax的状态码改变事件
=>xhr.onreadystatechange=function (){}
响应状态码
==>xhr.status
==>描述本次请求的状态
*/
const xhr = new XMLHttpRequest();
console.log(xhr.readyState);
xhr.open("GET", "get.php");
console.log(xhr.readyState);
xhr.onload = function () {
console.log(JSON.parse(xhr.responseText));
};
xhr.onreadystatechange = function () {
console.log(xhr.readyState);
if (xhr.readyState === 2) {
console.log("2响应体", xhr.responseText);
//2响应体
}
if (xhr.readyState === 3) {
console.log("3响应体", xhr.responseText);
//3响应体 {"user":"zhangsan","age":18}
//如果文件较大只返回部分
}
if (xhr.readyState === 4) {
console.log("4响应体", xhr.responseText);
//4响应体 {"user":"zhangsan","age":18}
//全部返回
}
console.log(xhr);
//低版本IE
if (xhr.status >= 200 && xhr.status < 300 && xhr.readyState === 4) {
console.log(xhr.responseText);
//{"user":"zhangsan","age":18}
}
};
xhr.send();
</script>
<?php
//谁请求我我就输出谁
$arr = array(
"user" => "zhangsan",
"age" => 18
);
echo json_encode($arr);
?>