我们使用jquery .load()一个形式为一个divjquery的交笨验证
然后,我们使用jQuery .POST()的形式向笨控制器即/应用/后
我们然后希望Codeigniter执行验证,但不确定如何返回到页面以显示验证错误?如果re .load()控制器不会重新初始化对象,我们会丢失数据?
我们以错误的方式接近这个吗?
我们使用jquery .load()一个形式为一个divjquery的交笨验证
然后,我们使用jQuery .POST()的形式向笨控制器即/应用/后
我们然后希望Codeigniter执行验证,但不确定如何返回到页面以显示验证错误?如果re .load()控制器不会重新初始化对象,我们会丢失数据?
我们以错误的方式接近这个吗?
将验证消息存储在来自控制器的会话中,然后在相应的视图/页面上显示它们,但是如果所有验证都由用户正确完成,则应该再次销毁会话。
我打算采取一些自由回答这个问题,因为我不认为我理解它。
首先,我对$.post()
了解不多,所以我会回答你的问题,就好像你是我们使用$.ajax()
,因为我知道这是我所知道的,我很确定它们是相似的。
我们接着要笨执行 验证,但不知道如何 返回一个页面来显示 验证错误?
您不返回到页面以显示错误,您将它们回显出来以便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({
data: myPostDataObj,
dataType: "json",
type: "POST",
success: function(data) {
alert(data.message);
},
error: function(data) {
alert(data.responseText);
}
});
您可以在jQuery的here阅读更多关于$.ajax()
,但基本上,您将发布的数据发送到您设置的任何控制器,它将采集该数据,并通过验证过程运行ss,如果失败,它会回应一些标准文本,ajax会将其作为var.responseText发送到您的错误函数。
如果它通过验证,你会对发布数据做一些事情,然后返回你想要的任何结果作为一个json对象,可以很容易地使用你的javascript函数。
我认为这可能是一个更好的解决方案,我希望这有助于解释一些事情。我希望。
哎呀!我可能误解了这个问题.... – bschaeffer 2010-02-25 04:01:39
bschaeffer非常漂亮! – 2010-02-25 16:05:44