需要考虑下浏览器的兼容性
<script>
/*
ajax请求数据的步骤:
1、创建ajax对象
2、配置请求方式和请求地址以及是否异步请求
3、浏览器向服务器发送请求
4、服务器接受请求
5、判断请求并响应数据
6、服务器向浏览器返回数据
7、浏览器渲染数据
*/
// 1、
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
console.log(xhr);
console.log(xhr.constructor);
} else {
// IE6-
var xhr = new ActiveXObject();
}
// 2、
// open("请求的方式","请求的地址",是否异步) ---后端人员给提供的
// true 异步 false 同步 默认是异步
xhr.open("GET", "ajax_info.txt", true);
// 3、
xhr.send();
// 4、
xhr.onreadystatechange = function () {
console.log(xhr);
console.log(xhr.readyState);//4
console.log(xhr.status);//200
// 5、
if (xhr.readyState == 4 && xhr.status == 200) {
// 6、
console.log(xhr.response);
// 7、
document.getElementById("box").innerText = xhr.response;
}
}
</script>