Jquery $.getJSON始终返回null
我正在努力使这项工作,但我不明白为什么它总是返回“请求失败”? json似乎是有效的(我知道jQuery对此很严格),也许是因为httpSJquery $.getJSON始终返回null,jquery,json,Jquery,Json,我正在努力使这项工作,但我不明白为什么它总是返回“请求失败”? 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.d
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");
});
可能是因为。如果是这种情况,您必须明确允许在服务器端获取JSON
我不知道你们在服务器端使用哪种技术。如果您使用的是ASP.NET MVC,则必须允许使用JsonRequestBehavior.AllowGet获取JSON。如果有疑问,请调试:
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");
});
如果后端(500403,…)有任何错误,您仍然会得到请求失败的消息
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");
}
});
如果您试图从其他域访问文件,则您的主题将访问。如果服务器未启用CORS,则无法通过Ajax加载文件。我可以使用jsonp发出请求,它允许跨域JSON请求。Thx很多,效果很好…嗯?为什么这与JSON劫持有关?@Felix Kling:我正在使用ASP.NET MVC,我必须使用JsonRequestBehavior.AllowGet
,否则javascript即使在同一个域上也无法加载JSON。原因是JSON劫持。好吧,但是如果服务在后端使用PHP呢?“由于JSON劫持,您必须显式允许在服务器端获取JSON”的语句是错误的,因为它是泛化的。实际问题可能是同一原产地政策。你能解释一下你改变了什么吗?为什么这样做有效?没有解释的代码通常没有多大帮助。“不允许跨域json ajax请求”:默认情况下不允许跨域ajax请求(无论json与否),但如果服务器启用CORS,则可以。我测试了这段代码,它可以工作……我猜使用“jsonp”的ajax调用在这里起到了作用