The jQuery.getJson()
function is an alias for an AJAX HTTP GET call, ie you are only using the ajax()
method of the library, so you are only using an asynchronous call and receiving a JSON in response, correct?
To do the same without importing the entire library you can use XMLHttpRequest
which is what the jQuery.ajax()
(and its jQuery.getJSON()
) method uses, since it is just a wrapper.
While with jQuery you would do
$.ajax('service/user/1234', {
method: 'POST',
contentType: 'application/json',
processData: false,
data: JSON.stringify({
name: 'João de Barros',
age: 34
})
})
.then(function success(userInfo) {
// userInfo será um objeto contendo propriedades como nome, idade,
// endereço, etc.
});
With XMLHttpRequest you would do so
var xhr = new XMLHttpRequest();
xhr.open('POST', 'service/user/1234');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
var userInfo = JSON.parse(xhr.responseText);
// userInfo será o mesmo objeto contendo propriedades como nome,
// idade, endereço, etc.
}
};
xhr.send(JSON.stringify({
name: 'João de Barros',
age: 34
}));
Ref.: