我有以下格式的 jquery json 请求:
JSON请求:
$.getJSON('http://xyz.com',function(result) {});
如果请求失败(服务器没有响应),我如何重定向到另一个域。例如“http://zxy.com”。(我们在另一台服务器上维护相同的代码)
我认为最好使用$.ajax()方法,error
或者success
如果服务器根据响应告诉你)。
然后使用它来重定向浏览器。
window.location = "http://www.google.com"
$.getJSON() 定义为:
jQuery.getJSON=function(url,data,callback){
return jQuery.get(url,data,callback,"json");
};
因此,默默地失败了。
要对错误做出反应,您需要直接使用 $.ajax() 函数,该函数允许您定义 onError 处理程序,如下所示:
$.ajax({
url: '...',
contentType:'json',
success:function(result,stat,xhr){
...
},
error:function(xhr,opts,err){
...
}
});
请参阅jQuery Ajax 错误处理,显示自定义异常消息以获取更多信息。
你试过这个吗?
function addImage(item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
}
var jqxhr = $.getJSON("http://xyz.com",function(data) {
$.each(data.items, function(i,item){ //sample
addImage(item);
})
.error(function() {
var jqxhrFailover = $.getJSON("http://zzz.com", function(data) {
$.each(data.items, function(i,item){ //sample
addImage(item);
}).error(function(){ alert('both failed!'); });