多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## AJAX - 服务器响应  由于 HTTP 响应是由服务端发出的,并且服务器做出响应需要时间(比如网速慢等原因),所以我们需要监听服务器响应的状态,然后才能进行处理。 * **状态行** `xhr.status`状态码,如200,304,404等; * **响应主体** `xhr.responseText`与`xhr.responseXML`都表示响应主体。  如需获得来自服务器的响应,请使用 XMLHttpRequest 对象的`responseText`或`responseXML`属性。 | 属性 | 描述 | | --- | --- | | responseText | 获得字符串形式的响应数据。 | | responseXML | 获得 XML 形式的响应数据。 | ## responseText 属性 如果来自服务器的响应并非 XML,请使用`responseText`属性。 ` responseText`属性返回字符串形式的响应,因此您可以这样使用: ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tryrun 1</title> </head> <body> <div id="view"> <p>点击下面的按钮,将 Ajax 请求回来的数据更新在该文本内</p> </div> <button type="button" id="btn">发起 Ajax 请求</button> <script> document.getElementById("btn").onclick = ajaxRequest; function ajaxRequest () { var xhr = new XMLHttpRequest(); xhr.open("GET", "https://www.w3cschool.cn/statics/demosource/ajax_info.txt", true); xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById("view").innerHTML = xhr.responseText; } } } </script> </body> ``` 提示:对于`responseText`属性,只有当[`readyState`属性](https://www.w3cschool.cn/ajax/ajax-xmlhttprequest-onreadystatechange.html)值变为4时,`responseText`属性才可用,因为这表明AJAX请求已经结束! ## responseXML 属性  如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用`responseXML`属性: 请求[cd\_catalog.xml](https://www.w3cschool.cn/statics/demosource/cd_catalog.xml)文件,并解析响应: ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> function loadXMLDoc() { var xmlhttp; var txt,x,i; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { xmlDoc=xmlhttp.responseXML; txt=""; x=xmlDoc.getElementsByTagName("ARTIST"); for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("myDiv").innerHTML=txt; } } xmlhttp.open("GET","/statics/demosource/cd_catalog.xml",true); xmlhttp.send(); } </script> </head> <body> <h2>My CD Collection:</h2> <div id="myDiv"></div> <button type="button" onclick="loadXMLDoc()">Get my CD collection</button> </body> </html> ```