2014-10-18 58 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