XMLHttpRequest Element
XMLHttpRequest Element
Contained in the QML Global Object (XmlHttpRequest), an
asynchronous web request can be initiated. The result can then be parsed as a JSON or XML result. Here is an example of sending a JSON-encoded JS object with a POST request:
function saveLevelRemote() {
var httpRequest = new XMLHttpRequest();
var postData = JSON.stringify(levelData);
httpRequest.open("POST", url, true);
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == httpRequest.DONE) {
console.debug("the level has been saved on the web server");
var serverResponse = httpRequest.responseText;
console.debug("saveLevelRemote() httpRequest result:", serverResponse, ", request: ", url, "postData:", postData);
if(!serverResponse) {
NativeUtils.displayMessageBox("Failed to save level to server");
return;
}
NativeUtils.displayMessageBox("Your level has been saved");
var result = JSON.parse(serverResponse);
var currentLevelId = result.levelId;
console.debug("the read id from the saved level is", currentLevelId);
}
}
httpRequest.send(postData);
}
And here is an example for parsing a GET request:
function getAllLevelsRemote() {
var httpRequest = new XMLHttpRequest();
httpRequest.open("GET", serverUrl, true);
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == httpRequest.DONE) {
var serverResponse = httpRequest.responseText;
console.debug("getAllLevelsRemote() httpRequest result:", serverResponse);
if(!serverResponse) {
NativeUtils.displayMessageBox("Failed to load levels from server");
return;
}
var result = JSON.parse(serverResponse);
}
}
}