tags:

views:

2593

answers:

4

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?

+15  A: 

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 ommited
 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
});
Paolo Bergantino
Great answer :-)
Graphain
+2  A: 

But unless i am mistaken this code wouldn't work:

3rdPartyObject.getCustomValue = function {
  var json = $.ajax({
    type: 'GET',
    url: 'whatever',
    dataType: 'json',
    success: function() { },
    data: {},
    async: false
  });

return json;
}

As $.ajax returns the XHR object not the parsed json object.

You would need to do something more like:

var jsonLoader = function(url){
    this.url = url;
    this.rawData = {};
    this.getRawData();
};

jsonLoader.prototype.getRawData = function(){

    var json = $.ajax({
     type: 'GET',
     url: this.url,
     dataType: 'json',
     success: this.getRawData(this),
     data: {},
     async: false
    });
};

jsonLoader.prototype. getRawData = function(self){
    return function(json){self.rawData = json;};
};

var loadMe = new jsonLoader("Data.json");
loadMe.rawData //has the parsed json object

In fact there is probably a much neater way of achieving the same

A: 
var jsonObjectInstance = $.parseJSON(
    $.ajax(
        {url: "json_data_plz.cgi", 
        async: false; 
        dataType: 'json'}
    ).responseText
);
ph1g
A: 

You can also use the following before making your call:

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

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

ex: 3rdPartyObject.getCustomValue = function { $.ajaxSetup( { "async": false } ); var result = $.getJSON('myUrl'); $.ajaxSetup( { "async": true } ); return result; }

Jonathan