Control a request when a jQuery Ajax call done

I'm using $.post() to call a server using Ajax and then using the JTemplate to write data to the current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the div element with the contents of the login page, forcing the user's eyes to witness a rare scene indeed.

How can I manage a redirect directive from an Ajax call with jQuery 1.9 ?


You must use json data to response to client. For example: In PHP file

<?php
//for example, data you want to response to client is a html string
$data = '<table></table>';
if($is_timeout && $is_ajax_request) {
   //shouldn't redirect, should return json_encode
   echo json_encode(array('timeout'=>1));
   die();
}else{
   echo json_encode(array('data'=>$data));
   die();
}

And in your javascript post you can edit below:

$.post('your_url_to_php_file',{data:data_to_post}, function(resp){
   var data = jQuery.parseJSON(resp);
   if(data.timeout) {
      alert("timeout");
      return;
   }else{
      $("#your_div").html(data.data);
   }
})
链接地址: http://www.djcxy.com/p/1968.html

上一篇: 什么是<

下一篇: 在完成jQuery Ajax调用时控制请求