ajax请求的五个步骤 ajax实现局部刷新( 二 )

总的来说 , readyState 属性的值有以下几种:
0 (未初始化) or (请求还未初始化) 1 (正在加载) or (已建立服务器链接) 2 (加载成功) or (请求已接受) 3 (交互) or (正在处理请求) 4 (完成) or (请求已完成并且响应已准备好)只读属性 XMLHttpRequest.status 返回了 XMLHttpRequest 响应中的数字状态码 。status 的值是一个无符号短整型 。在请求完成前 , status 的值为 0 。值得注意的是 , 如果 XMLHttpRequest 出错 , 浏览器返回的 status 也为0:
UNSENT(未发送) 0 OPENED(已打开) 0 LOADING(载入中) 200 DONE(完成) 200 var xhr = new XMLHttpRequest(); console.log('UNSENT', xhr.readyState); // readyState 为 0 xhr.open('GET', '/api', true); console.log('OPENED', xhr.readyState); // readyState 为 1 xhr.onprogress = function () { console.log('LOADING', xhr.readyState); // readyState 为 3 }; xhr.onload = function () { console.log('DONE', xhr.readyState); // readyState 为 4 }; xhr.send(null);只有在XMLHttpRequest对象完成了以上5个步骤之后 , 才可以获取从服务器端返回的数据 。因此 , 如果要获得从服务器端返回的数据 , 就必须要先判断XMLHttpRequest对象的状态:
const xhr = new XMLHttpRequest(); xmlHttpRequest.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { // do something here } } 4. 发送HTTP请求 XMLHttpRequest.send(data); 结束最后 , 附上一个简单的完整 AJAX 实例:
<button id="ajaxButton" type="button">Make a request</button> <script> var httpRequest; document.getElementById("ajaxButton").addEventListener('click', makeRequest); function makeRequest() { httpRequest = new XMLHttpRequest(); httpRequest.onreadystatechange = alertContents; httpRequest.open('GET', 'test.html'); httpRequest.send(); } function alertContents() { if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { alert(httpRequest.responseText); } else { alert('There was a problem with the request.'); } } } </script>

ajax请求的五个步骤 ajax实现局部刷新

文章插图
~
~


以上关于本文的内容,仅作参考!温馨提示:如遇健康、疾病相关的问题,请您及时就医或请专业人士给予相关指导!

「四川龙网」www.sichuanlong.com小编还为您精选了以下内容,希望对您有所帮助: