2013-09-22 13 views
0

當使用jQueryAjax,我通過整個網址阿賈克斯的url:在情況下URL都沒有了(不知),我怎麼會重定向到一個page not found頁面從內ajax本身? url go和.htaccess文件。jQuery的內部AJAX重定向的情況下,找不到網頁

$(document).ready(function() { 
    $('.link').click(function() { 
    var parentTag = 'check=checked'; 
    if(parentTag) { 
     // ajax call 
     $.ajax({ 
      type:"GET", 
      url:"/mylink/buyers/1/0/0", //If this failed, how do I redirect to something else from here? 
      data:parentTag, 
     dataType: 'json', 
      beforeSend:function(callBack){ 
       console.log('checked'); 
      }, 
      success: function(callBack){ 
       console.log('Success'); 
      }, 
      error: function(callBack){ 
       console.log('Failed'); 
      }, 
     }); 
    } 
    return false; 
    }); 
});  
+0

這不就是'error'回調做什麼?你可以用'this.status'找到http響應代碼(或者記錄'this',你會看到)。 – Rudie

回答

2

只需添加一個statusCode處理程序404,或任何其他HTTP status你想!

您也可以添加通用錯誤回調,但使用狀態代碼方法的優點是區分服務器的實際404(頁面未找到錯誤)和其他類型的連接問題。

$.ajax({ 
    /* ... */ 
statusCode: { 
    404: function() { 
     // server says: page not found; let's redirect to 404 page 
     window.location.href = "http://example.com/my/404/page"; 
    } 
    }, 
    error: function() { 
     // something else went wrong 
     alert('An unknown error occurred!'); 
    } 
}); 
2

只要把裏面window.location錯誤回調:

$(document).ready(function() { 
    $('.link').click(function() { 
    var parentTag = 'check=checked'; 
    if(parentTag) { 
     // ajax call 
     $.ajax({ 
      type:"GET", 
      url:"/mylink/buyers/1/0/0", //If this failed, how do I redirect to something else from here? 
      data:parentTag, 
     dataType: 'json', 
      beforeSend:function(callBack){ 
       console.log('checked'); 
      }, 
      success: function(callBack){ 
       console.log('Success'); 
      }, 
      error: function(callBack){ 
       console.log('Failed'); 
       window.location = "http://www.example.com"; 
      }, 
     }); 
    } 
    return false; 
    }); 
}); 
相關問題