Tim*_*Tim 2 validation jquery post codeigniter
我们使用jquery将.load()表单转换为div
然后我们使用jquery将.post()形成一个codeigniter控制器,即/ app/post
然后,我们希望Codeigniter执行验证,但不确定如何返回页面以显示验证错误?如果重新.load()控制器不会重新启动对象,我们会丢失数据?
我们是以错误的方式接近这个吗?
我会采取一些自由来回答这个问题,因为我认为我不理解它.
首先,我不太了解$.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();
}
Run Code Online (Sandbox Code Playgroud)
ajax:
$.ajax({
data: myPostDataObj,
dataType: "json",
type: "POST",
success: function(data) {
alert(data.message);
},
error: function(data) {
alert(data.responseText);
}
});
Run Code Online (Sandbox Code Playgroud)
你可以$.ajax()在这里阅读有关jQuery的更多信息,但基本上,你将发布数据发送到你设置的任何控制器,它将获取数据,在验证过程中运行它,如果它失败,它会回显一些标准文本ajax将发送到您的错误函数var.responseText.
如果它通过验证,你会对post数据做一些事情,然后返回你想要的任何结果作为json对象,可以很容易地在你的javascript函数中使用.
我认为这可能是一个更好的解决方案,我希望这有助于解释一些正在发生的事情.我希望.
| 归档时间: |
|
| 查看次数: |
3072 次 |
| 最近记录: |