JavaScript
x
16
16
1
const xhrRequest = new XMLHttpRequest();
2
3
xhrRequest.onload = function()
4
{
5
dump(xhrRequest.responseXML.documentElement.nodeName);
6
7
console.log(xhrRequest.responseXML.documentElement.nodeName);
8
9
10
11
}
12
13
xhrRequest.open("GET", "/website_url.xml")
14
xhrRequest.responseType = "document";
15
xhrRequest.send();
16
I’m trying to request a xml page from a page, but i’m unable to get certain line from xml in javascript. Thank you!
Advertisement
Answer
You can easily send requests to other pages with an AJAX http request found here: https://www.w3schools.com/js/js_ajax_intro.asp
Here is an example function:
JavaScript
1
11
11
1
function SendRequest(){
2
let xmlhttp = new XMLHttpRequest();
3
xmlhttp.onreadystatechange = function () {
4
if(this.readyState == 4 && this.status == 200){
5
// Success
6
}
7
};
8
xmlhttp.open("GET", "example.com", true);
9
xmlhttp.send();
10
}
11
Now, about getting a value from the xml document, you can use .getElementsByTagName()
. Notice that this is an array of elements so you have to append an index such as [0]
This would go inside the onreadystatechange
of the http request
JavaScript
1
5
1
if(this.readyState == 4 && this.status == 200){
2
let xmlDocument = this.responseXML;
3
console.log(xmlDocument.getElementsByTagName("TestTag")[0].childNodes[0].nodeValue);
4
}
5
So if the xml document had an element like:
JavaScript
1
2
1
<TestTag>Hello</TestTag>
2
the function would print Hello