简体   繁体   中英

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);
   }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM