$.getJSON always returns null
I'm trying to make this work but I don't understand why this always returns "Request Failed"? The json seems to be valid (I know jQuery is strict about this), maybe it's because of the 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");
});
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");
}
});
小提琴
请求应该使用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");
}
});
When in doubt, debug:
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");
});
If there is any error in the backend (500, 403, ...), you will get Request Failed
anyway.
上一篇: JSON输出作为响应发送以包装在字典中
下一篇: $ .getJSON总是返回null