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