我会冒昧地回答这个问题,因为我认为我不明白。
首先,我对$.post() 了解不多,所以我会回答你的问题,就好像你在使用$.ajax() 因为这是我所知道的,我很确定他们是类似。
然后我们希望 Codeigniter 执行
验证,但不知道如何
返回页面以显示
验证错误?
您无需返回页面来显示错误,而是将它们回显,以便 jQuery 可以接收输出(如 CI 视图文件),然后您可以根据需要处理结果。
使用$.ajax(),这就是我要做的......
CI 控制器:
if( ! $this->form_validation->run($my_form_rules))
{
// Set the status header so $.ajax() recognizes it as an error
$this->output->set_status_header(400);
// The error string will be available to the $.ajax() error
// function in the javascript below as data.responseText
echo validation_errors();
exit();
}
else
{
// Do something with the post data
$result = $this->do_something();
// Set the status header so $.ajax(0 recognizes a success
// and set the header to declare a json response
$this->output->set_status_header(200);
$this->output->set_header('Content-type: application/json');
// Send the response data as json which will be availible as
// var.whatever to the $.ajax() success function
echo json_encode($result);
exit();
}
ajax:
$.ajax({
data: myPostDataObj,
dataType: "json",
type: "POST",
success: function(data) {
alert(data.message);
},
error: function(data) {
alert(data.responseText);
}
});
您可以在 jQuery here 中阅读有关 $.ajax() 的更多信息,但基本上,您将发布数据发送到您设置的任何控制器,它会获取该数据,通过验证过程运行它,如果它失败,它会回显一些标准文本,ajax 将作为 var.responseText 发送到您的错误函数。
如果它通过验证,您将对发布的数据执行一些操作,然后将您想要的任何结果作为 json 对象返回,该对象可以轻松地在您的 javascript 函数中使用。
我认为这可能是一个更好的解决方案,我希望这有助于解释一些正在发生的事情。我希望。