XMLHttpRequest handles the sample code for returning data of in XML format
- 2020-03-29 23:52:31
- OfStack
Sample code:
//The callback function
function callback() {
//alert(xmlhttp.readyState);
//5. Receive response data
//Determining the state of an object is interactive completion
if (xmlhttp.readyState == 4) {
//Determine whether the HTTP interaction was successful
if (xmlhttp.status == 200) {
//Use responseXML to receive the DOM object of the XML data object
var domObj = xmlhttp.responseXML;
if (domObj) {
//<message>123123123</message>
//GetElementsByTagName is used in the dom to get element nodes by tag name, returning an array
var messageNodes = domObj.getElementsByTagName("message");
if (messageNodes.length > 0) {
//Gets the text content in the message node
//The text in the message tag is the byte point of the element node corresponding to the message tag in the dom, and the firstChild can get the firstChild node of the current node
//The node corresponding to the text content can be obtained in the following ways
var textNode = messageNodes[0].firstChild;
//For a text node, the text content of the text node can be returned via nodeValue
var responseMessage = textNode.nodeValue;
//Displays the data on the page
//Find the element node corresponding to the div tag in the dom way
var divNode = document.getElementById("result");
//Sets the HTML content in the element node
divNode.innerHTML = responseMessage;
} else {
alert("XML Data format error, original text content is: " + xmlhttp.responseText);
}
} else {
alert("XML Data format error, original text content is: " + xmlhttp.responseText);
}
} else {
alert(" Error!! ");
}
}
}