简体   繁体   English

jQuery JSONP回调没有触发

[英]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/ ). 我正在使用jQuery进行跨域AJAX请求,但我的回调函数没有触发(请参阅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 "=?" 从jQuery 1.5开始,将jsonp选项设置为false可防止jQuery将“?callback”字符串添加到URL或尝试使用“=?” for transformation. 转型。 In this case, you should also explicitly set the jsonpCallback setting. 在这种情况下,您还应该显式设置jsonpCallback设置。 For example, { jsonp: false, jsonpCallback: "callbackName" } 例如,{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/ ). 但是,如果我没有指定回调而只是处理成功事件中的数据,那么它就可以工作(参见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? 我是否误解了如何使用jQuery发出JSONP请求?

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. 正如您摘录的文档中所述,如果服务器需要一个名为callback的参数,那么jQuery足够聪明,可以为您填写空白。 Bitbucket does use this parameter name, so you get a URL like: Bitbucket确实使用此参数名称,因此您可以获得如下URL:

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

jquery1234_5678 would actually be an automatically generated function name for your callback. jquery1234_5678实际上是一个自动生成的回调函数名。 Bitbucket then returns something like: Bitbucket然后返回如下内容:

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. 如果Bitbucket期望一个不同的参数名称,你可以使用它作为jsonp的值。 So for example, if you passed: 例如,如果你通过了:

jsonp: "functionName"

the URL would look something like: URL看起来像这样:

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. 如果您不希望jQuery生成函数名,则只需要jsonpCallback

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM