gpt4 book ai didi

jQuery JSONP 回调未触发

转载 作者:行者123 更新时间:2023-12-01 00:53:18 25 4
gpt4 key购买 nike

我正在使用 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 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/ )。

$.ajax({
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(error);
},
success: function(data) {
jsonpCallback(data);
}
});

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

最佳答案

正如您摘录的文档中所述,如果服务器需要一个名为 callback 的参数,jQuery 足够智能,可以为您填补空白。 Bitbucket 确实使用此参数名称,因此您会得到如下 URL:

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

jquery1234_5678 实际上是为回调自动生成的函数名称。然后 Bitbucket 返回如下内容:

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

因此该函数被调用。另外,您可以将成功部分简化为( demo ):

success: jsonpCallback

如果 Bitbucket 需要不同的参数名称,您可以将其用作 jsonp 的值。例如,如果您通过了:

jsonp: "functionName"

URL 看起来像:

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

但是响应是一样的。

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

关于jQuery JSONP 回调未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9238504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com