The native javascript implementation parses XML documents and strings
- 2021-01-19 21:56:07
- OfStack
Written before 1 article "use the method of analytical XML jquery" link is https: / / www ofstack. com article / 54842. htm, article explained in detail the jQuery and string conversion method, focuses on javascript xml operation here.
The general code is as follows:
var XMLHttp = null;
if (window.XMLHttpRequest) { // Modern Browser
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; // parsing XML The document
var XMLDoc = XMLHttp.responseText; // parsing XML string
var XMLDom = (new DOMParser()).parseFromString(XMLDoc, "text/xml");
// I'm going to write the asynchronous code here
console.log(XMLDom);
console.log("world"); // After the world
}
}
};
XMLHttp.open("get", "test1.xml", true);
XMLHttp.send();
// The non-asynchronous code is written here
console.log("hello"); // Came first hello
}
Step 1: Create XMLHTTPREQUEST:
var XMLHttp = null;
if (window.XMLHttpRequest) { // Modern Browser
XMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE5/IE6
}
Step 2: Check ONREADYSTATECHANGE (non-asynchronous, not required) :
if (XMLHttp !== null) {
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState === 4) {
if (XMLHttp.status === 200 || XMLHttp.status === 304) {
// I'm going to write the asynchronous code here
}
}
};
XMLHttp.open("get", "test1.xml", true);
XMLHttp.send();
// The non-asynchronous code is written here
}
Step 3: Parse XML documents or strings (asynchronous) :
XMLHttp.onreadystatechange = function() {
if (XMLHttp.readyState === 4) {
if (XMLHttp.status === 200 || XMLHttp.status === 304) {
// var XMLDom = XMLHttp.responseXML; // parsing XML The document
var XMLDoc = XMLHttp.responseText; // parsing XML string
var XMLDom = (new DOMParser()).parseFromString(XMLDoc, "text/xml");
// I'm going to write the asynchronous code here
console.log(XMLDom);
}
}
};
Step 4: Parse XML documents or strings (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();
// The non-asynchronous code is written here
// var XMLDom = XMLHttp.responseXML; // parsing XML The document
var XMLDoc = XMLHttp.responseText; // parsing XML string
var XMLDom = (new DOMParser()).parseFromString(XMLDoc, "text/xml");
// I'm going to write the asynchronous code here
console.log(XMLDom);
}