$.getJSON 不工作。为什么?
$.getJSON is not working. Why?
我可以使用 $.get() 从 ipinfo.io 获取数据,如下所示:
$.get("http://ipinfo.io", function(response) {
alert(response.city);
}, "jsonp");
以上有效。但是当我为此目的尝试使用 $.getJSON 时,我不再获取数据了。我的代码是:
$.getJSON(
"http://ipinfo.io/?callback=callback?", function(response) {
alert(response.city);
}
).fail(function(){
console.log("failed");
});
“?回调=回调?” url 中的部分在 ipinfo.io documentation 中有说明。
有时显示 "Too many requests" 没关系。但大多数时候它会毫无错误地失败。我做错了什么?
根据 docs
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.
因此,将您的代码从 callback=callback?
更改为 callback=?
,如下所示:
$.getJSON(
"http://ipinfo.io/?callback=?", function(response) {
alert(response.city);
}
).fail(function(){
console.log("failed");
});
如果 web 服务使用的参数不同于 jsonp 回调的回调参数,您将相应地更改该部分。例如,如果您的服务器使用 results=
而不是 url 将是 "http://coolwebservice.io/?results=?"
将 "http://ipinfo.io/?callback=callback?"
更改为 "http://ipinfo.io/?callback=?
。
$.getJSON(
"http://ipinfo.io/?callback=?", function(response) {
alert(response.city);
}
).fail(function(){
console.log("failed");
});
旧 post 但像我这样的人可能正在寻找答案。
将文件保存在 html 或 php 中,即使其中的代码可能是 json。
之后,如果您希望输出为 json,则使用 get 或 GETJSON,后者是后者。
我可以使用 $.get() 从 ipinfo.io 获取数据,如下所示:
$.get("http://ipinfo.io", function(response) {
alert(response.city);
}, "jsonp");
以上有效。但是当我为此目的尝试使用 $.getJSON 时,我不再获取数据了。我的代码是:
$.getJSON(
"http://ipinfo.io/?callback=callback?", function(response) {
alert(response.city);
}
).fail(function(){
console.log("failed");
});
“?回调=回调?” url 中的部分在 ipinfo.io documentation 中有说明。
有时显示 "Too many requests" 没关系。但大多数时候它会毫无错误地失败。我做错了什么?
根据 docs
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.
因此,将您的代码从 callback=callback?
更改为 callback=?
,如下所示:
$.getJSON(
"http://ipinfo.io/?callback=?", function(response) {
alert(response.city);
}
).fail(function(){
console.log("failed");
});
如果 web 服务使用的参数不同于 jsonp 回调的回调参数,您将相应地更改该部分。例如,如果您的服务器使用 results=
而不是 url 将是 "http://coolwebservice.io/?results=?"
将 "http://ipinfo.io/?callback=callback?"
更改为 "http://ipinfo.io/?callback=?
。
$.getJSON(
"http://ipinfo.io/?callback=?", function(response) {
alert(response.city);
}
).fail(function(){
console.log("failed");
});
旧 post 但像我这样的人可能正在寻找答案。 将文件保存在 html 或 php 中,即使其中的代码可能是 json。 之后,如果您希望输出为 json,则使用 get 或 GETJSON,后者是后者。