Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a version of $getJSON that doesn't use a call back?

Tags:

json

jquery

I am implementing a callback for a 3rdParty javascript library and I need to return the value, but I need to get the value from the server. I need to do something like this:

3rdPartyObject.getCustomValue = function {
   return $.getJSON('myUrl');
}

getJson uses XMLHttpRequest which (I believe) has both synchronous and asynchronous behaviors, can I use the synchronouse behavior?

like image 203
tpower Avatar asked Jun 01 '09 06:06

tpower


People also ask

What is getJSON?

The getJSON() method is used to get JSON data using an AJAX HTTP GET request.

What does getJSON return?

getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request. The method returns XMLHttpRequest object.


3 Answers

Looking at the jQuery source code, this is all $.getJSON does:

getJSON: function( url, data, callback ) {
    return jQuery.get(url, data, callback, "json");
},

And this is all $.get does:

get: function( url, data, callback, type ) {
    // shift arguments if data argument was omitted
    if ( jQuery.isFunction( data ) ) {
        callback = data;
        data = null;
    }

    return jQuery.ajax({
        type: "GET",
        url: url,
        data: data,
        success: callback,
        dataType: type
    });
},

No black magic there. Since you need to customize stuff other than the basic $.getJSON functionality, you can just use the low-level $.ajax function and pass the async option as false:

$.ajax({
    type: 'GET',
    url: 'whatever',
    dataType: 'json',
    success: function() { },
    data: {},
    async: false
});
like image 118
Paolo Bergantino Avatar answered Nov 05 '22 01:11

Paolo Bergantino


You can also use the following before making your call:

$.ajaxSetup( { "async": false } );

I do not know the scope of the "async" property, I suspect that it is a global config. So consider whether you want to change this back to true after your synchronous call.

example:

3rdPartyObject.getCustomValue = function { 
    $.ajaxSetup( { "async": false } );
    var result = $.getJSON('myUrl');
    $.ajaxSetup( { "async": true } );
    return result;
}
like image 20
Jonathan Avatar answered Nov 05 '22 01:11

Jonathan


var jsonObjectInstance = $.parseJSON(
    $.ajax(
        {
           url: "json_data_plz.cgi", 
           async: false, 
           dataType: 'json'
        }
    ).responseText
);
like image 44
ph1g Avatar answered Nov 05 '22 00:11

ph1g