【问题标题】:How to handle form render and ajax response in the same action?如何在同一操作中处理表单渲染和 ajax 响应?
【发布时间】:2012-12-06 03:19:11
【问题描述】:

我的 ProjectsController 中有 create() 方法,它使用 AJAX 呈现表单并保存其数据:

class ProjectsController extends AppController
{    
    public function create()
    {
        if ($this->request->is('post'))
        {
            $this->Project->create();
            $this->request->data['Project']['created_by'] = $this->Auth->user('id');
            if ($this->Project->save($this->request->data))
            {
                ...
            } else {
                ...
            }
        }

    }

如果数据已保存,我如何仅传递成功消息,如果不是 ajax 请求,如何呈现我的表单?我不能设置autoRender false '因为它还得渲染表单

这是处理 jax 请求的最正确方法吗?如果不行怎么办?

【问题讨论】:

  • 我会使用 post 参数来指示请求是 ajax。

标签: php ajax cakephp cakephp-2.0


【解决方案1】:

检测 AJAX:

你可以使用:

if($this->request->is('ajax')) {

用 ajax 做任何你想做的事,其余的用明显的 'else' 来做。

处理它:

大概是这样的:

if ($this->request->is('ajax')) {
    //process the ajax response
    $this->render('/Ajax/json');

} else {
    if($this->request->is('post')) {
        //process the post
    }
    //set variables for the view...etc etc

}

另一种选择 - 单独的功能:

或者,只有两种不同的操作也很常见——一种用于 ajax,另一种用于您想要的任何其他操作。这是我喜欢的方式,因为我宁愿没有 if() 块。但是 - 各有特色,而且我经常看到两者都使用过。

public function create_ajax() { ... }

public function create() { ... }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 2021-03-24
    • 2017-03-10
    • 1970-01-01
    • 2021-08-09
    • 2016-12-19
    • 1970-01-01
    相关资源
    最近更新 更多