Alex Rivera | Logout

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

Asked 2009-06-01T06:04:34.613
39

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?

Edit
Report

1 Answer

3

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

answered 2009-07-07T14:29:34.483

Your Answer