网页请求(Ajax)
2018-02-02 本文已影响2人
廖马儿
ajax = Asynchronous JavaScript and XML
XMLHttpRequest实例,就是ajax的具体实现。
<script>
let xhr = new XMLHttpRequest(); // ajax
</script>
通过 xhr
我们可以实现异步请求。
<script>
let xhr = new XMLHttpRequest(); // ajax
xhr.open("POST", "test.txt", true);
// 我们向后端请求数据的方式 http请求 post get
// 请求地址
// 异步的方式请求还是同步方式请求. true 是异步
xhr.send(); // 向后端进行数据的发送
// xhr 状态只要发生改变了 我们就可以进行数据的操作了
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 || xhr.status == 200) {
// xhr.readyState (0, 1, 2, 3, 4) 五个级别,表示我们当前数据结构处理的阶段。数据处理完成是4
// xhr.status 状态码 404:页面无法被找到
// 200 请求成功
// 301 302 网页请求重定向了(301:永久重定向, 302:在、临时重定向)
// 404 页面不能找到
// 500 服务器故障
console.log(xhr.responseXML); // 打印结果
}
}
</script>