【问题标题】:CakePHP cancel redirect to view after submitting ajax add action提交ajax添加操作后CakePHP取消重定向到视图
【发布时间】:2010-08-16 12:42:56
【问题描述】:

我正在尝试通过 AJAX 提交表单并在提交表单后阻止重定向。我不明白我为什么会遇到这个问题,因为我将 autoRender 设置为 false。

控制器代码

 function add() {
    $this->autoRender = false;
    if (!empty($this->data)) {
        $this->data['Comment']['user_id'] = $this->Auth->user('id');
        $this->Comment->create();
        if ($this->Comment->save($this->data)) {
        }
    }
}

JS 事件处理程序

$(".submit_comment").live("submit",commentSubmitHandler);
function commentSubmitHandler(event){
$.ajax({
    type: "post",
    url: $("#webroot").val() + "comments/add",
    data: data,
    dataType: "json",
    success: function(data){
        alert("win");
    },
    error: function(data){
        alert("fail");
    }
});
return false;

}

表单数据已提交并保存得很好,但它为什么离开页面?此外,它似乎在完成 js 之前就已经这样做了,因为警报实际上从未发生过。因此,控制器操作“add”有一个明确的直接重定向。

【问题讨论】:

    标签: jquery ajax cakephp


    【解决方案1】:

    尝试在表单之外添加指向提交 js 的链接,以测试提交是否以这种方式工作。如果是这样,那么您可能需要将按钮从 type="submit" 更改为 type="button"。可能是“提交”按钮实际上是在提交表单。

    另一种方法是验证<form>标签是通过js提交,而不是发布到控制器中的add函数。

    此外,通过清除 tmp/cache/persistant 中的缓存文件来检查以确保没有缓存任何内容(以防万一 - 我已经看到它发生了)。

    【讨论】:

    • 如果你使用其他缓存引擎,clear_cache 插件值得安装。它为您提供了一个外壳(通过 cake clear_cache 调用)并清理 tmp 文件夹以及其他 tmp 内容。亲切的问候
    • 感谢 CD,您将提交更改为按钮的建议奏效了。提交实际上是提交表单。我的粗心错误。
    【解决方案2】:

    试着把$this->autoRender = false;

    在 if 的 save 或最后一行...就像

    function add() {
    
        if (!empty($this->data)) {
            $this->data['Comment']['user_id'] = $this->Auth->user('id');
            $this->Comment->create();
            if ($this->Comment->save($this->data)) {
               ....
               $this->autoRender = false;
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      我怀疑您的表单正在提交,这让我认为您的事件处理程序末尾的 return false 语句没有按照您的想法执行。 .submit_comment 元素是表单还是按钮?

      【讨论】:

        猜你喜欢
        • 2015-10-11
        • 2014-08-05
        • 1970-01-01
        • 1970-01-01
        • 2014-01-25
        • 1970-01-01
        • 2017-11-13
        • 2021-10-02
        • 1970-01-01
        相关资源
        最近更新 更多