jquery(ajax)重定向到另一个域

我有以下格式的jquery json请求:

JSON请求:

$.getJSON('http://xyz.com',function(result) {}); 

如果请求失败(服务器未响应),我如何重定向到另一个域。 例如“http://zxy.com”。(我们在另一台服务器上维护相同的代码)

你试过这个吗?

 function addImage(item) { $("").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!'); }); 

我认为如果服务器根据响应告诉你,使用$ .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 Ajaxerror handling,显示自定义exception消息以获取更多信息。