我正在努力使这项工作,但我不明白为什么这总是返回“请求失败”? json似乎是有效的(我知道jQuery对此很严格),也许是因为httpS?
var geo_url = "https://spapi.cdnspstr.com/api/get_geo_ip";
var jqxhr = $.getJSON(geo_url, {
format: "json"
})
.done(function (json_data) {
alert("currency: " + json_data.data.currency);
})
.fail(function () {
alert("Request Failed");
});
答案 0 :(得分:1)
var geo_url = "https://spapi.cdnspstr.com/api/get_geo_ip";
$.ajax({
url: geo_url,
data: {
format: "json"
},
crossDomain: true,
dataType: 'jsonp',
success: function (json_data) {
alert("currency: " + json_data.data.currency);
alert("city: " + json_data.data.city);
},
error: function () {
alert("Request Failed");
}
});
答案 1 :(得分:1)
请求应该使用jsonp来完成,因为不允许跨域json-ajax请求
$.ajax("https://spapi.cdnspstr.com/api/get_geo_ip",{
dataType: 'jsonp',
success: function(json_data) {
alert("currency: " + json_data.data.currency);
},
error: function() {
alert("Request Failed");
}
});
答案 2 :(得分:0)
这可能是由于JSON hijacking。如果是这种情况,则必须明确允许在服务器端获取JSON。
我不知道您在服务器端使用哪种技术。如果您使用的是ASP.NET MVC,则必须允许使用JsonRequestBehavior.AllowGet
答案 3 :(得分:0)
如有疑问,请调试:
var geo_url = "https://spapi.cdnspstr.com/api/get_geo_ip";
var jqxhr = $.getJSON(geo_url, {
format: "json"
})
.done(function (json_data) {
alert("currency: " + json_data.data.currency);
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
alert("Request Failed");
});
如果后端有任何错误(500,403,...),那么无论如何都会得到Request Failed
。