I previously wrote an article "How to use jquery to parse XML". The link is http://www.jb51.net/article/54842.htm. The previous article explained jQuery and strings in detail The method of mutual conversion, here focuses on the operation of javascript xml.
The total code is as follows:
var XMLHttp = null; if (window.XMLHttpRequest) { //现代浏览器 XMLHttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { XMLHttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE5/IE6 } if (XMLHttp !== null) { XMLHttp.onreadystatechange = function() { if (XMLHttp.readyState === 4) { if (XMLHttp.status === 200 || XMLHttp.status === 304) { // var XMLDom = XMLHttp.responseXML; //解析XML文档 var XMLDoc = XMLHttp.responseText; //解析XML字符串 var XMLDom = (new DOMParser()).parseFromString(XMLDoc, "text/xml"); //异步代码写这里 console.log(XMLDom); console.log("world"); //后出现world } } }; XMLHttp.open("get", "test1.xml", true); XMLHttp.send(); //非异步代码写这里 console.log("hello"); //先出现hello }
The first step is to create XMLHTTPREQUEST:
var XMLHttp = null; if (window.XMLHttpRequest) { //现代浏览器 XMLHttp = new XMLHttpRequest(); } else if (window.ActiveXObject) { XMLHttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE5/IE6 }
The second step is to detect ONREADYSTATECHANGE (not required for non-asynchronous):
if (XMLHttp !== null) { XMLHttp.onreadystatechange = function() { if (XMLHttp.readyState === 4) { if (XMLHttp.status === 200 || XMLHttp.status === 304) { //异步代码写这里 } } }; XMLHttp.open("get", "test1.xml", true); XMLHttp.send(); //非异步代码写这里 }
The third step, parse XML document or string (asynchronous):
XMLHttp.onreadystatechange = function() { if (XMLHttp.readyState === 4) { if (XMLHttp.status === 200 || XMLHttp.status === 304) { // var XMLDom = XMLHttp.responseXML; //解析XML文档 var XMLDoc = XMLHttp.responseText; //解析XML字符串 var XMLDom = (new DOMParser()).parseFromString(XMLDoc, "text/xml"); //异步代码写这里 console.log(XMLDom); } } };
The fourth step, parse XML document or string (non-asynchronous):
if (XMLHttp !== null) { // XMLHttp.onreadystatechange = function() { // if (XMLHttp.readyState === 4) { // if (XMLHttp.status === 200 || XMLHttp.status === 304) {} // } // }; XMLHttp.open("get", "test1.xml", false); XMLHttp.send(); //非异步代码写这里 // var XMLDom = XMLHttp.responseXML; //解析XML文档 var XMLDoc = XMLHttp.responseText; //解析XML字符串 var XMLDom = (new DOMParser()).parseFromString(XMLDoc, "text/xml"); //异步代码写这里 console.log(XMLDom); }