2014-08-29 37 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