无法使Ajax在CakePHP中工作 [英] Can't get ajax to work in CakePHP

查看:70
本文介绍了无法使Ajax在CakePHP中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在CakePHP 2.3中运行ajax请求。我正在处理此帖子:
简单的ajax示例与cakephp 2.3.0

I am trying to run an ajax request in CakePHP 2.3. I am working off of this post: simple ajax example with cakephp 2.3.0

我无法正常工作,这是我的代码:

I cant get it to work, here is my code:

$("#node-form-save").click(function(){
        event.preventDefault();
        var firstName = $("#node-form-first-name").val();
        var lastName = $("#node-form-last-name").val();
        var dob = $("#node-form-dob").val();
        $.ajax({
            url:'/persons/create',
            type: 'GET',
            datatype: 'json',
            data: {firstName: firstName, lastname: lastName, dob:dob},
            success: function(data){
                alert("succes");
                }
        });
        $('#modal-pop').jqmHide();

    })

我从一个简单的测试开始,看看是否达到了成功功能,但是我没有警报。我的代码有什么问题?网址正确。 url / persons有效,当我输入/ persons / create时,我得到一个CakePHP屏幕,说我没有视图(但是我不想要一个,我在做ajax。
我列出了我的控制器(PersonsController .php)

I started with a simple test, to see if the sucess function is reached, but I get no alert. What is wrong with my code? The url is correct. The url /persons works, and when I type in /persons/create I get a CakePHP screen saying that I have no view (but I don't want one, I am doing ajax. I list my controller (PersonsController.php) below

class PersonsController extends AppController
{
public $helpers = array('html', 'form');

public function index()
{

}

public function create()
{

}
}

现在,这样我就可以使用基本功能。

I left the functions blank for now, just so I can get the basic functionality working.

推荐答案

首先:为什么要获取

您说过您不想要视图,但是您的代码无处指定该视图。对于ajax,为避免呈现视图和布局,请执行以下操作

You said you don't want a view, but your code nowhere specifies that. For ajax, and to avoid rendering the view and the layout, do this

public function create() {
    $this->autoRender = false;
}

此外,如果这样做,您将无法获得任何回报,因此在操作中,您需要回显值,以便ajax可以接收它。

Also, if you do that, you won't get anything in return, so in the action, you need to echo the values so ajax can recieve it.

提示,您可以通过简单的检查将要使用ajax执行的功能和正常方式分开

And a tip, you can separate the functions you want to excecute with ajax and the normal way with a simple check

public function create() {
    if( $this->request->is('ajax') ) {
        $this->autoRender = false;
        echo 'hello result';
        return;
    }

    //else, handle this action as a normal one and render a view and whatever
}

这篇关于无法使Ajax在CakePHP中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆