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

时间:2015-02-10 09:14:04

标签: javascript php jquery ajax yii

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

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

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

请告诉我。谢谢。

5 个答案:

答案 0 :(得分:3)

您可以使用" beforeSend" ajax事件,你可以检查你的会话,如果它已过期你可以做其他事情:

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

点击此处了解详情:http://api.jquery.com/Ajax_Events/

答案 1 :(得分:3)

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

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

答案 2 :(得分:2)

此代码可以解决您的问题。

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

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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

使用 ajaxComplete 事件。

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