CakePHP AJAX调用 [英] CakePHP AJAX call

查看:88
本文介绍了CakePHP AJAX调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 CakePHP ,这是我在这个框架上的第一个项目。我将向 UsersController check_username()操作发送输入的值。并用 check_username()返回的字符串填充id na 的元素。到目前为止我做的是:

I am using CakePHP and this is my first project on this framework. I am going to send the value of an input to UsersController's check_username() action. And fill an element having id na with the string returned by check_username(). So far what I did is:

//in my form
<input type="text" name="data[User][username]" style="width: 60%" required="required" id="username" oninput="check_username(this.value)">
<label style="margin-left: 20px; color: red" id="na">Not Available!</label>

//after the form
<script type="text/javascript">
    function check_username(un) {
        $.ajax({
            type: 'POST',
            url: '/oes/users/check_username',
            data: {username:un},
            cache: false,
            dataType: 'HTML',
            beforeSend: function(){
                $('#na').html('Checking...');
            },
            success: function (html){
                $('#na').val(html);
            }
        });
    }
</script>

//and my check_username() is
public  function check_username(){
    return 'Test string';
}

但这不工作。

推荐答案

这可能是您的 check_username 控制器操作。 CakePHP方式是使用 JsonView 类发送任何数据throw XHR(参见 http://book.cakephp.org/2.0/en/views/json-and-xml-views.html )。它允许您使用.json扩展名(例如:/oes/users/check_username.json)调用任何操作,并以序列化的JSON格式获取响应,而无需手动转换beetween数组数据和JSON。

It could be problem with your check_username controller action. CakePHP-way is to use JsonView class to send any data throw XHR (see http://book.cakephp.org/2.0/en/views/json-and-xml-views.html). It allows you to call any action with .json extension (ex.: /oes/users/check_username.json) and get response in serialized JSON format without manual conversion beetween array data and JSON.

这种方法是建议为您的需要,但不是义务,当然。

This method is recommended for your needs, but not obligated, of course.

现在我认为CakePHP试图渲染 check_username 查看,但是不能这样做,创建它。尝试将您的操作代码更改为这样:

Now I think that CakePHP tries to render check_username view, but could not do this because you have not specified or created it. Try to change your action code to something like this:

public function check_username(){
     $this->autoRender = false;
     echo 'Test string';
}

此外,尽量不要在将来使用这样的代码构造。

Also, try not to use such code construction in the future.

这篇关于CakePHP AJAX调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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