2010-03-10 36 views
6

$.getJSON()文档状态:为什么jQuery不自动附加JSONP回调?

If the specified URL is on a remote server, the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

$.ajax()文档的jsonp数据类型国家(重点煤矿):

Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback.

如此看来,如果我叫$.getJSON()有跨网域网址,额外的“回调=?”参数应该自动添加。 (文档的其他部分支持这种解释。)

但是,我没有看到这种行为。如果我不添加“回调=?”明确地说,jQuery不正确地生成一个XMLHttpRequest(由于我无法读取跨域响应,所以它返回空数据)。如果我确实明确地添加它,jQuery正确地发出<脚本>请求。

下面是一个例子:

var URL = "http://www.geonames.org/postalCodeLookupJSON" + 
    "?postalcode=10504&country=US"; 

function alertResponse(data, status) { 
    alert("data: " + data + ", status: " + status); 
} 

$.getJSON(URL, alertResponse); 
// alerts "data: null, status: success" 

$.getJSON(URL + "&callback=?", alertResponse); 
// alerts "data: [object Object], status: undefined" 

那么这是怎么回事?我误解了文档还是忘记了一些东西?

不言而喻,这不是一个大问题,但我创建了一个web API,并且我特意将回调参数设置为“回调”,希望能够很好地适应jQuery的使用。

谢谢!

(编辑:我cross-posted this在jQuery的论坛,如果你有兴趣)

回答

7

试试这个:

var URL = "http://www.geonames.org/postalCodeLookupJSON" + 
    "?postalcode=10504&country=US"; 
function alertResponse(data, status) { 
    alert("data: " + data + ", status: " + status); 
} 
$.ajax({ 
    url: URL, 
    dataType: 'jsonp', 
    jsonpCallback: 'alertResponse', 
}); 
+1

在你的例子中,你实际上是指'jsonpCallback:'alertResponse'',是的,那么我就不需要明确地添加“callback =?”参数。但是这比'$ .getJSON()'的优雅更加冗长。它会很好,如果$ .getJSON()工作记录... – 2010-03-12 07:53:31

3

是的,我想你误会了。如文档所述,$.getJSON$.ajax({datatype: 'json'....的快捷方式。除非添加callback=?参数,否则它永远不会产生JSONP调用。

+0

嗯...我真的误解了吗?我引用的句子非常明确:“如果指定的URL位于远程服务器上,请将该请求视为JSONP。” – 2010-03-12 07:48:28

+0

你是对的。这很混乱。 – 2010-03-12 20:53:24

0

我使用下面的代码,

$阿贾克斯({ 网址:网址, 数据类型: 'JSONP', 成功:功能(数据) {// 做一些 } 错误:函数(jqXHR,textStatus,errorThrown){}, jsonpCallback:'login_callback', });

但是,回调有时会附加在URL的末尾,有时不在IE中。 虽然它在铬和FF工作正常。