jquery post codeigniter验证

时间:2010-02-25 03:21:03

标签: jquery validation codeigniter post

我们正在使用jquery将.load()表单转换为div

然后我们使用jquery来.post()形成一个codeigniter控制器,即/ app / post

然后我们希望Codeigniter执行验证但不确定如何返回页面以显示验证错误?如果re re .load(),控制器不会重新启动对象,我们会丢失数据吗?

我们是以错误的方式接近这个吗?

2 个答案:

答案 0 :(得分:6)

我会采取一些自由来回答这个问题,因为我认为我不理解它。

首先,我对$.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发送给你的错误函数。

如果它通过验证,你会对post数据做一些事情,然后返回你想要的任何结果作为json对象,可以很容易地在你的javascript函数中使用。

我认为这可能是一个更好的解决方案,我希望这有助于解释一些正在发生的事情。我希望。

答案 1 :(得分:1)

将验证消息存储在来自控制器的会话中,然后在相应的视图/页面上显示它们,但如果用户正确完成所有验证,则应再次销毁会话。