问题描述
我正在使用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'
});
根据文档:
但是,如果我不指定回调,而是仅在成功事件中处理数据,则它会起作用(请参见 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回调未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!