xml request javascript code example
Example 1: xml http request
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "filename", true);
xhttp.send();
Example 2: Working with XML in JavaScript
const fs = require("fs");
const { parseString, Builder } = require("xml2js");
const xml = fs.readFileSync("data.xml").toString();
parseString(xml, function (err, data) {
console.log(data);
data.people.person[0].$.id = 2;
const builder = new Builder();
const xml = builder.buildObject(data);
fs.writeFileSync("data.xml", xml, function (err, file) {
if (err) throw err;
console.log("Saved!");
});
});
Example 3: javascript http request
function _GET_REQUEST(url, response) {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
response(this.responseText);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function _POST_REQUEST(url, params, response) {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
response(this.responseText);
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
}
_GET_REQUEST('http://url.com', (response) => {
console.log(response);
});
_POST_REQUEST('http://url.com', 'parameter=sometext', (response) => {
console.log(response);
});