2012-09-22 21 views
-1

我有以下格式jquery的JSON請求:的jQuery(阿賈克斯)重定向到另一個域

JSON請求:

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

如果請求失敗(服務器未響應),我怎麼重定向到另一個域。例如「http://zxy.com」(我們在另一臺服務器上維護相同的代碼)

回答

0

你試過這個嗎?

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!'); }); 
+0

謝謝,但我如何從數據庫中獲得結果,如第二個url中的「result.username」等(如果發生錯誤) – user655334

+0

您需要傳遞循環值。 – turtlepick

+0

我試圖把上面的例子。嘗試使它適用於一臺服務器,然後級聯調用.error() – turtlepick

3

我認爲這可能是更好的使用$.ajax()error方法或success如果服務器告訴你基於響應)。

然後使用它來重定向瀏覽器。

window.location = "http://www.google.com" 
2

$ .getJSON()被定義爲:

jQuery.getJSON=function(url,data,callback){ 
    return jQuery.get(url,data,callback,"json"); 
}; 

正因爲如此,默默失敗。

作出反應,你需要使用直接在$阿賈克斯()函數,它允許你定義一個onError的處理程序,如錯誤:

$.ajax({ 
    url: '...', 

    contentType:'json', 

    success:function(result,stat,xhr){ 
     ... 
    }, 

    error:function(xhr,opts,err){ 
     ... 
    } 
}); 

進一步的信息,請參閱jQuery Ajax error handling, show custom exception messages