【问题标题】:jquery post codeigniter validationjquery发布codeigniter验证
【发布时间】:2011-01-20 20:14:52
【问题描述】:

我们正在使用 jquery 将表单加载()到 div 中

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

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

我们是否以错误的方式处理这个问题?

【问题讨论】:

    标签: jquery validation codeigniter post


    【解决方案1】:

    我会冒昧地回答这个问题,因为我认为我不明白。

    首先,我对$.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 函数中使用。

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2013-04-10
        • 2019-03-12
        • 1970-01-01
        • 2017-04-30
        • 1970-01-01
        • 2013-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多