Send JSON
by Lars Holm Jensen
HTML
<button type="button" onclick="sendJSON()" >Send</button>
JavaScript
var getJSON = function(method, url, data, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
var responseTypeAware = 'responseType' in xhr;
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
if (responseTypeAware) {
xhr.responseType = 'json';
}
xhr.onreadystatechange = function() {
var status = xhr.status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
if (status.toString().indexOf("2") === 0) {
successHandler && successHandler(
responseTypeAware
? xhr.response
: JSON.parse(xhr.responseText)
);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send(data);
};
window.sendJSON = function() {
var dataobject = {
title: 'foo',
body: 'bar',
userId: 1
};
var mydata = JSON.stringify(dataobject);
getJSON("post","http://jsonplaceholder.typicode.com/posts",mydata, function(data){
console.log("Success: " + alert(JSON.stringify(data)));
}, function(data){
console.log("Error: " + data);
});
};