jQuery JSONP Callback not firing

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:

https://api.bitbucket.org/.../?callback=jquery1234_5678

jquery1234_5678 would actually be an automatically generated function name for your callback. Bitbucket then returns something like:

jquery1234_5678({
    "node": "someId",
    "path": "filename",
    "data": "content"
})

so the function is called. Also, you can simplify (demo) the success part to:

success: jsonpCallback

If Bitbucket expected a different parameter name, you would use that as the value of jsonp. So for example, if you passed:

jsonp: "functionName"

the URL would look something like:

https://api.bitbucket.org/.../?functionName=jquery1234_5678

but the response would be the same.

You only need jsonpCallback if you don't want jQuery to generate the function name.

链接地址: http://www.djcxy.com/p/47544.html

上一篇: jQuery,ajax和jsonp的问题

下一篇: jQuery JSONP回调没有开火