我正在使用jQuery ajax和Codeigniter创建一个应用程序。现在,当我的会话到期时,它会检查CI的$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文档输出类中找到了标题
使用$.post()
的fail
回调方法获取error
.fail(function(e,xhr, o) {
// how can I fetch the contents from here?
});
ajaxError
是全局调用的,它与ajaxSetup
方法
刚刚回答了我自己的问题。谢谢你的回答,它给了我一个主意。原因是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');
}
}