Skip to content

Instantly share code, notes, and snippets.

@jmcker
Forked from john-doherty/javascript-http-get.js
Last active July 15, 2018 23:11
Show Gist options
  • Save jmcker/3e822693a34e0eaa8955a42cceb0a716 to your computer and use it in GitHub Desktop.
Save jmcker/3e822693a34e0eaa8955a42cceb0a716 to your computer and use it in GitHub Desktop.
Simple, pure JavaScript HTTP Get function (QML, IE8+, Chrome, Safari, Firefox, PhoneGap/Cordova)
/**
* GET contents of a URL
* @access private
* @param {string} url - url to get
* @param {function} error - function to call if there is an error
* @param {function} callback - function to call if success
* @returns {void}
*/
function httpGet(url, error, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200 || (xhr.status === 0 && xhr.responseText !== '')) {
callback({
url: url,
status: 200,
body: JSON.parse(xhr.responseText)
});
}
else {
error({
url: url,
status: xhr.status,
body: JSON.parse(xhr.responseText)
});
}
}
};
xhr.send();
}
import 'javascript-ajax-get.js' as HttpRequest
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
property var response: undefined
property int responseCode: 0
signal responseReceived()
Component.onCompleted: {
// Send the request when rendering finishes
HttpRequest.httpGet("https://api.github.com/repos/symboxtra/jenkins-discord-webhook/releases/latest",
function(obj) {
responseCode = obj.status;
response = obj.body;
ResponseReceived();
},
function(obj) {
responseCode = obj.status;
response = obj.body;
ResponseReceived();
}
);
}
onResponseReceived: {
if (responseCode !== 200) {
console.log("Response returned code: " + responseCode);
return;
}
console.log("Response received!");
// Do stuff with the response object
console.log(response.url);
}
}
httpGet("https://api.github.com/repos/symboxtra/jenkins-discord-webhook/releases/latest",
function(obj) {
alert("Response " + obj.status + ": \n" + JSON.stringify(obj.body, undefined, 4));
},
function(obj) {
alert(JSON.stringify(obj.body, undefined, 4));
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment