views:

657

answers:

4

How do I use beforeSend callback in $.getJSON(cross domain).

More specifically $.getJSON is call is to a YQL service Like

select * from html where url=”http://www.yahoo.com

A: 

I think you want to use $.ajaxStart() and $.ajaxStop(). Those will let you show and hide a loading gif on ajax/JSON requests. It also does the right thing if there are multiple ajax requests going on.

Nick Craig-Wood
+1  A: 

$.getJSON is just a short cut function to the $.ajax function

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
   });
}, 
getJSON: function( url, data, callback ) {
    return jQuery.get(url, data, callback, "json");
},

So if you ever need to do anything more then the basic getJSON calls just use $.ajax like:

jQuery.ajax({
    url: url,
    dataType: "json",
    beforeSend: function(){
        $('.loading').show();
    }
});

The other option is to use the $.ajaxSend and $.ajaxComplete functions but this will make those functions be called before and after every ajax call.

PetersenDidIt
+1  A: 

The only purpose of beforeSend is to get at the raw XHR object (normally for setting HTTP headers on it). You don't need it for kicking off spinners and the like. This code here (from @petersendidit):

jQuery.ajax({
    url: url,
    dataType: "json",
    beforeSend: function(){
        $('.loading').show();
    }
});

Is better written like this:

$('.loading').show();
jQuery.ajax({
    url: url,
    dataType: "json"
});

Which means, unless you need any advanced options in jQuery.ajax, your original plan to use jQuery.getJSON is just fine. So you say you want to show a loading GIF, just do this and forget about beforeSend.

jQuery(".someSpinnerImage").show();
jQuery.getJSON("http://www.somedomain.com/someurl", function(data) {
    // Do something with data
    jQuery(".someSpinnerImage").hide();
}
darkporter
A: 

I think you are using JSONP for calling a script from another server. I did my homework and there isn't no beforeSend event on JSONP call.

Kreker