需要在所有 ajax 和 jquery post 函数之前调用一个 javascript 函数

Need to call one javascript function before all ajax and jquery post function

我有各种函数,使用 ajax 和 $.post 语法调用服务器函数。但是当会话过期并且页面未刷新时,我的 ajax 代码将无法工作。在此我想将页面重定向到登录控制器。 因为这是 ajax 调用,所以我的重定向代码不起作用。

是否有任何代码或 JavaScript/jQuery 函数在任何其他 jquery ajax 和 post 函数之前执行。

我在服务器端使用 PHP(Yii 框架)。

请告诉我。谢谢。

您可以使用 "beforeSend" ajax 事件来检查您的会话,如果它已过期,您可以执行其他操作:

$.ajax({
   beforeSend: function(){
     // Handle the beforeSend event
   },
   complete: function(){
     // Handle the complete event
   }
   // ......
 });

查看此以获取更多信息:http://api.jquery.com/Ajax_Events/

jQuery 提供了一组 AJAX events 你可以在请求生命周期中监听。在您的情况下,您可以订阅在 document 上触发的 ajaxError 事件,以便在请求因未授权而失败时做出反应:

$(document).on('ajaxError', function(el, xhr) {
    if (xhr.status == 401) {
        alert('Unauthorized');
    }
});

这段代码可以解决您的问题。

$(document).bind("ajaxSend", function(){
   //DO Someting..
});

注意beforeSend是本地事件,ajaxSend是全局事件

        /***
         * Global Ajax call which gets excuted before each $.ajax and $.post function
         * at server side chk session is set or destroy 
         ***/
        $(document).on('ajaxStart', function()
        {
            $.post( BASEURL+"/login/chkLogin",
            {},
            function(data)
            {
                if (data == 'login') {
                  window.location = BASE_URL+'/login'; //Load the login page
                }
                else
                {
                    //alert('all okay! go and execute!'); 
                    //No need to write anything in else part 
                    //or can say no need of else block 
                    //if all okay normal ajax action is processed
                }
            });     
      });

这就是我想要的。完美地发挥我的功能。感谢您的所有回答和评论。我从你那里得到了很大的参考。

使用 ajaxComplete 事件。

$( document ).ajaxComplete(function() { 
  window.location.href = "/login";
});