简体   繁体   English

完成jQuery Ajax调用时控制请求

[英]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. 我正在使用$.post()使用Ajax调用服务器,然后使用JTemplate将数据写入当前页面。 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. 在这种情况下, jQuerydiv元素替换为登录页面的内容,迫使用户的眼睛确实见证了罕见的场景。

How can I manage a redirect directive from an Ajax call with jQuery 1.9 ? 如何使用jQuery 1.9Ajax调用管理重定向指令?

You must use json data to response to client. 您必须使用json数据来响应客户端。 For example: In PHP file 例如:在PHP文件中

<?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: 在您的javascript post您可以在下面进行编辑:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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