jQuery JSONP回调未触发 [英] jQuery JSONP Callback not firing

查看:72
本文介绍了jQuery JSONP回调未触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery进行跨域AJAX请求,但是我的回调函数未触发(请参见 http://jsfiddle.net/zC8z5/).

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'
});

根据文档:

从jQuery 1.5开始,将jsonp选项设置为false可防止jQuery 从将?callback"字符串添加到URL或尝试使用 "=?"进行转化.在这种情况下,您还应该明确设置 jsonpCallback设置.例如,{jsonp:false,jsonpCallback: "callbackName"}

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" }

但是,如果我不指定回调,而是仅在成功事件中处理数据,则它会起作用(请参见 http ://jsfiddle.net/2gBRT/).

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);
    }
});

我是否误解了如何使用jQuery发出JSONP请求?

Have I misunderstood how to make JSONP requests with jQuery?

推荐答案

如您摘录的文档中所述,如果服务器需要一个名为callback的参数,则jQuery足够聪明,可以为您填充空白. Bitbucket确实使用此参数名称,因此您将获得如下网址:

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实际上将是您的回调自动生成的函数名称.然后,Bitbucket返回以下内容:

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

如果Bitbucket期望使用不同的参数名称,则可以将其用作jsonp的值.例如,如果您通过:

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

jsonp: "functionName"

URL类似于:

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

但响应将是相同的.

如果您不希望jQuery生成函数名称,则只需要jsonpCallback.

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

这篇关于jQuery JSONP回调未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆