2017-04-18 54 views
0

我有一個在codeigniter框架中開發的web應用程序。在Ajax調用中會話過期時避免顯示登錄頁面

我的問題是,我有很多ajax調用在我的後端,現在在ajax調用如果會話過期,其顯示的登錄頁面,我想加載動態數據的地方。

如何在不改變所有ajax調用的情況下解決此問題?

$.ajax({ 
    url: "<?= base_url("controller/method") ?>", 
    data: {key1: value1,key2: value2}, 
    type: "POST", 
    dataType: "HTML" 
    success: function(){ 
     // here i'm processing the response. 
    } 
}); 
+0

你可以發佈Ajax代碼嗎? – Gntem

+0

如果會話過期,您應該獲得Web應用程序中正常的登錄頁面。現在「動態數據」是什麼意思? –

+0

@ Mr.Phoenix我添加了我的ajax代碼。 – user7573053

回答

0

確定,所以存在用於這樣的簡單的解決方案,

在服務器側上;

if($_SESSION['loggedin']=='false') //assuming the login check 
    header('app-stat : loggedout') //send custom header to client 

現在在客戶端,您檢查ajax調用中的標頭。

成功的功能就像;

success: function(data, textStatus, request){ 
    if(request.getResponseHeader('app-stat')=='loggedout') 
    { 
      //do what ever you want 
    } 
    else{ 
      //enjoy 
    } 
}, 

好的,爲你已經添加的500個Ajax解決方案是;

$(document).ajaxSuccess(function() { 
    //I think now you know what to do 
}); 
+0

這個解決方案很好,但我必須在所有的ajax調用中改變這個(我的後端有超過500個ajax調用)。 – user7573053

+0

添加解決方案請檢查。 –

+0

我不喜歡這些成功的錯誤。這就是HTTP錯誤代碼的用途。 – apokryfos

0

在你的控制器

class Controller_name extends CI_Controller { 

    public function __construct() 
    { 
     parent::__construct(); 
     $user_id = $this->session->userdata('user_id'); // Session id of user 
     if(!$user_id || $user_id == '') 
     { 
      if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') 
      { // Checking if ajax request received or not 

       echo json_encode(array('status' => FALSE,'msg' => 'You are not logged in')); 
       die; 
      } 

     } 
    } 
} 

而在你的Ajax請求

$.ajax({ 
    url: "<?= base_url("controller/method") ?>", 
    data: {key1: value1,key2: value2}, 
    type: "POST", 
    dataType: "json" 
    success: function(resp){ 
     if(resp.status == false) 
     { 
     alert(resp.msg); 
     } 
    } 
}); 

注:這裏我使用數據類型:「JSON在Ajax請求