在表单提交时,我使用jQuery$.ajax发出一个AJAX请求:
$('form.sendMessage').off('submit').on('submit', function (e){
e.preventDefault();
var form = $('form.sendMessage');
if (form.valid(){
$.ajax({
url: base_url + <?=$moduleUrl?> + '/sendMessage',
data: form.serialize();
type: 'POST',
beforeSubmit: function () {
if (!confirm('Are you sure you want to send this message?')) {
return false;
}
},
success: function () {
toastr.success("Message sent", "Success");
},
error: function (response) {
toastr.error(response, "Error");
}
});
}
)
});
在控制器中,对于发出请求的sendMessage方法,我有一个条件,如果传递该条件,将继续到sendingMessage方法:
public function sendMessage()
{
$post = $this->input->post(null, true);
if ($this->input->is_ajax_request() && !empty($post)) {
try {
$this->sendingMessage($post);
} catch (Exception $e) {
$this->output->set_status_header('401')
->set_output($e->getMessage());
}
}
}
private function sendingMessage($post)
{
if (!empty($post) && (int)$post['device'] > 0 && isset($post['message'])) {
$this->load->model('protectee/device_messages');
// save in db
$data = [
'device_id' => $post['device'],
'user_id' => $_SESSION['UserID'],
'message' => $post['message'],
'date' => date('Y-m-d H:i:s'),
];
$messageId = $this->device_messages->insertMessage($data);
if ($messageId > 0) {
$this->insertCommand($post['device'], 'MSG', '<br>' . $post['message']);
} else {
throw new Exception('Message could not be send! Please try again..');
}
} else {
throw new Exception('An error occured! Please try again..');
}
}
当我提交表单时,它转到一个空白页面,URL更改为.../sendMessage.
因此,我认为,它不符合成为AJAX_Requestif ($this-\>input-\>is_ajax_request() && !empty($post)
的条件.