2014-08-29 30 views
0

假設我有以下的Ajax調用:

$.ajax({ 
    type: 'POST', 
    url: 'some_url', 
    dataType: 'json', 
    data: { some: data }, 
    success: function(data){ 
     // Success message will be shown. 
     window.setTimeout(function(){location.reload()}, 2000); 
    }, 
    failed : function(data){ 
     // Error message will be shown. 
     window.setTimeout(function(){location.reload()}, 2000); 
    } 
}); 

,並在服務器端我有這樣的事情:

function delete_json(){ 
    $post = $this->input->post(); 
    if(!empty($post)){ 
     // Do something crazy here and return the result as JSON. 

     header('Content-Type: application/json'); 
     echo json_encode($data); 
     exit; 
    }else{ 
     // CURRENTLY THIS DOES NOT WORK...... 
     // IT DOES NOT REDIRECT THE PAGE AS INTENDED 
     redirect('some_url', 'refresh'); 
    } 
} 

我怎麼能強制重定向用戶到另一個頁面,如果如果ajax調用仍然期待結果被返回?

這將是一個很好的方法嗎?

+1

Ajax調用通過JSON重定向URL和阿賈克斯成功 – 2014-08-29 04:22:09

+0

你需要在阿賈克斯的成功功能 – 2014-08-29 04:22:58

回答

2

因爲這是一個AJAX調用,它不會對瀏覽器產生明顯的影響。您將不得不在客戶端執行重定向。在異步回

$.ajax({ 
    type: 'POST', 
    url: 'some_url', 
    dataType: 'json', 
    data: { some: data }, 
    success: function(data){ 
     // Success message will be shown. 
     if(data.good===true){ 
      window.setTimeout(function(){location.reload()}, 2000); 
     } 
     else{ 
      window.location.href("http://my.url.here"); 
     } 

    }, 
    failed : function(data){ 
     // Error message will be shown. 
     window.setTimeout(function(){location.reload()}, 2000); 
    } 
}); 
+0

感謝@Alex重定向重定向,這就是我的想法。我想我需要從客戶端做重定向。 – Jeremy 2014-08-29 04:56:32