jquery post codeignitervalidation

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

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

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

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

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

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

首先,我不太了解$.post() ,所以我会回答你的问题,好像你是我们使用的是$.ajax()因为这就是我所知道的,我很确定他们很相似。

然后,我们希望Codeigniter执行validation,但不确定如何返回页面以显示validation错误?

您没有返回到显示错误的页面,您将它们回显出来以便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中有关$.ajax()更多信息,但基本上,你将发布数据发送到你设置的任何控制器,它会获取数据,在validation过程中运行它,如果失败,它会回响输出一些标准文本,ajax将作为var.responseText发送给您的错误函数。

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

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