Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple HTTP JSON Request in QML
import bb.cascades 1.0
Page {
content: Container {
Label {
id: emailLabel
text: qsTr("Email")
}
Label {
id: urlLabel
text: qsTr("URL")
}
Label {
id: sinceLabel
text: qsTr("Since")
}
Label {
id: bioLabel
text: qsTr("Bio")
}
Button {
id: requestButton
text: "World Domination"
onClicked: {
request('http://someurlgoeshere.com', function (o) {
// log the json response
console.log(o.responseText);
// translate response into object
var d = eval('new Object(' + o.responseText + ')');
// access elements inside json object with dot notation
emailLabel.text = d.email
urlLabel.text = d.url
sinceLabel.text = d.since
bioLabel.text = d.bio
});
}
}
}
// this function is included locally, but you can also include separately via a header definition
function request(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = (function(myxhr) {
return function() {
callback(myxhr);
}
})(xhr);
xhr.open('GET', url, true);
xhr.send('');
}
}
{
"email": "bill@microsoft.com",
"url": "http://www.microsoft.com",
"since": "2011-09-08T08:06:48Z",
"bio": "I am awesome"
}
@obscuren

This comment has been minimized.

Copy link

@obscuren obscuren commented Sep 16, 2014

Cheers! Though you might want to alter it with the following:

return function() {
    if(myxhr.readyState === 4) callback(myxhr)
}

To prevent the callback being fired multiple times without response text.

@kounkou

This comment has been minimized.

Copy link

@kounkou kounkou commented Jun 3, 2018

You're awesome !

@xlwu25

This comment has been minimized.

Copy link

@xlwu25 xlwu25 commented Jun 5, 2018

Awesome!

@Markkyboy

This comment has been minimized.

Copy link

@Markkyboy Markkyboy commented Sep 8, 2019

Cheers! Though you might want to alter it with the following:

return function() {
    if(myxhr.readyState === 4) callback(myxhr)
}

To prevent the callback being fired multiple times without response text.

Thanks to you too!, 5 years later, your info is still useful! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment