I’m making a cross-domain AJAX request using jQuery but my callback function is not firing (see http://jsfiddle.net/zC8z5/).
function jsonpCallback(response){
$('#code').text(response.data);
}
$.ajax({
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(error);
},
success: function() {
alert("success");
},
jsonp: false,
jsonpCallback: 'jsonpCallback'
});
As per the docs:
As of jQuery 1.5, setting the jsonp option to false prevents jQuery
from adding the “?callback” string to the URL or attempting to use
“=?” for transformation. In this case, you should also explicitly set
the jsonpCallback setting. For example, { jsonp: false, jsonpCallback:
“callbackName” }
However, if I don’t specify a callback and instead just handle the data in the success event it works (see http://jsfiddle.net/2gBRT/).
$.ajax({
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(error);
},
success: function(data) {
jsonpCallback(data);
}
});
Have I misunderstood how to make JSONP requests with jQuery?
As noted in the docs you excerpted, if the server expects a parameter called
callback, jQuery is smart enough to fill in the blank for you. Bitbucket does use this parameter name, so you get a URL like:jquery1234_5678would actually be an automatically generated function name for your callback. Bitbucket then returns something like:so the function is called. Also, you can simplify (demo) the success part to:
If Bitbucket expected a different parameter name, you would use that as the value of jsonp. So for example, if you passed:
the URL would look something like:
but the response would be the same.
You only need
jsonpCallbackif you don’t want jQuery to generate the function name.