Luigino
Luigino

Reputation: 779

Synchronous equivalent way of $.getJSON

I have this code sample which returns data in JSON format to put into slickGrid:

$.getJSON(url, function(data) { 
    $.each(data, function() { dataReturn.push(this); });
    ...
    myDataView.setItems(dataReturn); 
    ...
});

but I am looking for a synchronous way and I tried something like this:

var dataReturn = JSON.stringfy( $.ajax({url:"...", async: false }).responseText );
myDataView.setItems(dataReturn);

but seems it isn't really the same...what I have missed?

Thanks in advance Cheers Luigi

Upvotes: 3

Views: 2326

Answers (2)

R. Oosterholt
R. Oosterholt

Reputation: 8080

You are missing the dataType argument (see jQuery documentation):

$.getJSON() is a shorthand for:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

Try to avoid synchronous calls though. Quote from jQuery doc (see async prop):

Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

You might want to try jQuery Deferreds like this:

var jqxhr = $.getJSON(url);
jqxhr.done(function(data) {
    $.each(data, function() { dataReturn.push(this); });
        ...
        myDataView.setItems(dataReturn); 
        ...
    });
});

Upvotes: 0

void
void

Reputation: 36703

Use $.ajax and set async : false like this

$.ajax({
        url:url, 
        dataType : 'json',
        async : false,
        success : function(data) { 
            $.each(data, function() { dataReturn.push(this); });
             ...
            myDataView.setItems(dataReturn); 
            ...
            }
});

Upvotes: 5

Related Questions