如何让 jQuery 的 $.getJson 处理 JSONP 结果?
How do I get a jQuery's $.getJson to work on a JSONP result?
我有以下 Javascript 代码:
$.getJSON('data.jsonp?callback=abcde', function(data) {
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
console.log(errorThrown);
})
但它会导致parseError
。这是传入的文本:
abcde({"data":"value"});
这是错误:
SyntaxError: Unexpected token a in JSON at position 0
我可能遗漏了一些非常明显的东西,但我已经完成了研究但找不到。有人可以指出我遗漏了什么吗?
尝试使用 callback=?
而不是 callback=abcde
。来自 documentation:
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax()
for more details.
jQuery 查找此特定字符串,然后替换其内部生成的函数名称。
$.getJSON('data.jsonp?callback=?', function(data) {
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
console.log(errorThrown);
})
如果您需要使用自己的回调函数,我认为您必须使用 $.ajax()
而不是 $.getJSON()
快捷方式。
$.ajax({
url: "data.jsonp",
type: "get",
dataType: 'jsonp',
jsonp: "abcde"
})
.done(function(data) {
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
console.log(errorThrown);
});
我有以下 Javascript 代码:
$.getJSON('data.jsonp?callback=abcde', function(data) {
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
console.log(errorThrown);
})
但它会导致parseError
。这是传入的文本:
abcde({"data":"value"});
这是错误:
SyntaxError: Unexpected token a in JSON at position 0
我可能遗漏了一些非常明显的东西,但我已经完成了研究但找不到。有人可以指出我遗漏了什么吗?
尝试使用 callback=?
而不是 callback=abcde
。来自 documentation:
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in
$.ajax()
for more details.
jQuery 查找此特定字符串,然后替换其内部生成的函数名称。
$.getJSON('data.jsonp?callback=?', function(data) {
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
console.log(errorThrown);
})
如果您需要使用自己的回调函数,我认为您必须使用 $.ajax()
而不是 $.getJSON()
快捷方式。
$.ajax({
url: "data.jsonp",
type: "get",
dataType: 'jsonp',
jsonp: "abcde"
})
.done(function(data) {
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
console.log(errorThrown);
});