ihue ihue - 1 month ago 5
Javascript Question

What are the alternative ways of making an Ajax call?

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.

Answer

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'
Comments