我有各种使用ajax和$.post语法的函数,这些语法调用服务器函数。但是,当会话过期且页面未刷新时,我的ajax代码将无法工作。在此,我想将页面重定向到登录控制器。因为这是ajax调用,所以我的重定向代码无法工作。
是否有在任何其他jquery、ajax和post函数之前执行的代码或JavaScript/jQuery函数。
我在服务器端使用PHP(Yii框架)。
请让我知道。谢谢。
发布于 2015-02-10 09:59:31
/***
* 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
}
});
});这就是我想要的。完美地发挥我的功能。谢谢你的回答和评论。我从你那得到了一个重要的推荐信。
发布于 2015-02-10 09:16:44
您可以使用"beforeSend“ajax事件来检查会话,如果会话过期,可以执行其他操作:
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......
});查看这个以获得更多信息:事件/
发布于 2015-02-10 09:23:30
jQuery提供了一组在请求生命周期中可以侦听的AJAX事件。在您的示例中,您可以订阅在ajaxError上触发的document事件,以便在请求作为未经授权的情况失败时作出反应:
$(document).on('ajaxError', function(el, xhr) {
if (xhr.status == 401) {
alert('Unauthorized');
}
});https://stackoverflow.com/questions/28427854
复制相似问题