2014-10-18 60 views
0

我使用jQuery ajax和Codeigniter創建了一個應用程序。現在,當我的會話到期時,如果它是真的,我將它的$ this-> session-> userdata('user_data')設置爲空,我將它設置爲未授權的標題狀態401。並應返回正在返回的自定義數據。

這裏是我的代碼:

if(empty($this->session->userdata('user_data'))) { 
     if($this->input->is_ajax_request()){ 
      $this->output 
       ->set_content_type('application/json') 
//set cutom output. 
       ->set_output(json_encode(array('response_code' => 401, 'message' => 'unauthorized'))) 
       ->set_status_header('401'); 
     } 
     else { 
      //redirect to login page 
      redirect('login/logout'); 
     } 
    } 

,你可以看到我設置的自定義輸出爲JSON。 我的Ajax請求是

$(document).ajaxError(function(e,xhr,o) { 
     // how can I fetch the contents from here? 
    }); 
    var url = /*url for my controller */; 
    var params = /* objects to be passed */; 
    $.post(url, params).done(function(e){ 
    console.log('success'); 
    }); 

來源: 我發現頭中CI documentation output class

回答

0

只是回答了我自己的問題。謝謝你的回答,它給了我一個主意。原因是它是從預期的響應附加了json。例如。期待「你好!」作爲迴應它給我

hello{'response_code': 401, 'message': 'unauthorized'} 

我只需要json部分。不是響應字符串。

我所做的是在我的PHP的一部分,我檢查仍有活動會話:

if(empty($this->session->userdata('user_data'))) { 
     if($this->input->is_ajax_request()){ 
      $this->output 
       ->set_content_type('application/json') 
       ->set_status_header('401'); 
       //I passed the data to die(). in order to disregard the previous response 
       // and get the expected response 
       // {'response_code': 401, 'message': 'unauthorized'} 
       die(json_encode(array('response_code' => 401, 'message' => 'unauthorized'))); 
     } 
     else { 
      //redirect to login page 
      redirect('login/logout'); 
     } 
    } 
1

用戶fail回調方法與$.post()得到error

.fail(function(e,xhr, o) { 
     // how can I fetch the contents from here? 
    }); 

ajaxError被調用全球範圍內,這是任何用戶評論與ajaxSetup方法

+0

是的,我們對此深感抱歉,是我宣佈在全球範圍的。使用$(document).ajaxError(function(e,xhr,o){});請參閱我的編輯。 – loki9 2014-10-18 05:54:12

+0

好的,你有什麼迴應?,使用**螢火蟲**看到阿賈克斯respose – Girish 2014-10-18 06:09:13