I'm wondering what is the best way to make an AJAX call.
This is what I have right now, and it works just fine.
$.ajax({
url: "/rest/computer",
type: "GET",
dataType: "json",
data: {
assessmentId: "123",
classroomId: "234"
},
success: function(objects) {
// .... code ....
}
});
I'm currently seeking another ways of making an Ajax call. If there is, should I use my approach ?
Should I move an Ajax call into it own function and call it back ?
Any suggestions on this will be much appreciated.
Yes there are some other ways to call ajax
jQuery
var get_data = function(){
var result = false;
$.get('/rest/computer').done(function(awesome_data){
result = awesome_data;
});
return result;
}
$.getJSON
$.getJSON( '/rest/computer', { assessmentId:"123", classroomId:"234"})
.done( function(resp){
// handle response here
}).fail(function(){
alert('Oooops');
});
If you're not using jQuery in your code, this answer is for you
Your code should be something along the lines of this:
function foo() {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "/rest/computer");
httpRequest.send();
return httpRequest.responseText;
}
var result = foo(); // always ends up being 'undefined'
There is a new async Fetch API that all of the modern browsers support:
fetch('./api/projects', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'Beispielprojekt',
url: 'http://www.example.com',
})
})
.then(response => { console.log(response); })
.catch(error => { console.error(error); });
See this post for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With