为什么我的ajax呼叫没有完成,它正在发送,但是我收到来自CakePHP的404响应?

Dan*_*ham 0 php ajax jquery cakephp

我有以下ajax调用:

$("#welcome a.close").click(function(e) {
    $.ajax({
        type: "GET",
        url: "/visitors/hide_welcome",
        success: function(){
            $("#welcome").hide(0);
            e.preventDefault();
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

针对我网站的以下内容:

<div id="welcome">
    <h2>Welcome  <a class="close" href="Javascript:;"></a></h2>
    <div class="left">
    </div>
    <div class="right">
        <div class="loginElement">

        </div>
    </div>
    <div class="clear"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

使用以下代码来回答ajax请求:

<?php
class VisitorsController extends AppController {

        function hide_welcome() {
                if($this->RequestHandler->isAjax()) {
                        $this->Session->write('Welcome.hidden', true);
                        echo 'Success.';
                }
                else {
                        echo 'I am, in fact, here.<br>';
                        $this->autoRender = false;
                }
        }

}
?>
Run Code Online (Sandbox Code Playgroud)

这很直接.它调用/visitors/hide_welcome设置一个会话变量,注意到它们隐藏了欢迎.但它似乎没有完成.如果我在它的任何一侧发出警报,就像这样:

$("#welcome a.close").click(function(e) {
    alert("Begin.");
            $.ajax({
        type: "GET",
        url: "/visitors/hide_welcome",
        success: function(){
            $("#welcome").hide(0);
            e.preventDefault();
        }
    });
            alert("End.");
});
Run Code Online (Sandbox Code Playgroud)

他们会触发.但是放入的警报success会被忽略.这同样适用于errorcomplete.这在我的测试机上运行得很好.有问题的页面肯定在那里,我可以用ajax来达到它.Firebug没有报告任何内容,错误控制台也没有报告. Success根本不会开火.

最奇怪的部分是,如果我手动重新加载,欢迎会消失,表明ajax调用确实触发了.它永远不会回来.这里发生了什么?我的智慧结束了.有人看到我还没有吠叫的树吗?

解:

CakePHP应该自动检测ajax调用.但在这种情况下,事实并非如此.结果它运行了我为Ajax编写的代码,但是当它找不到视图时返回404.解决方案是附加$this->autoRender= false;到ajax处理控制器功能的末尾.之后一切都很美妙.

Nic*_*ver 5

认为根据您的症状,您将重定向到<a class="close">您点击指向的任何URL - 因为不会阻止默认行为.

e.preventDefault()呼叫应在基本方法,而不是回调,像这样发生的:

$("#welcome a.close").click(function(e) {
    $.ajax({
        type: "GET",
        url: "/visitors/hide_welcome",
        success: function(){
            $("#welcome").hide(0);
        }
    });
    e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)