CakePHP的AJAX调用 [英] CakePHP AJAX call

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

问题描述

我使用 CakePHP的,这是我在这个框架的第一个项目。我将输入的值发送到 UsersController中 check_username()的行动。并填写了具有元素ID 与check_username由返回的字符串()。到目前为止,我所做的是:

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';
}

不过,这是行不通的。任何人都知道为什么或如何修改它,这样它的工作原理?

But this isn't working. Anybody know why or how to modify it so that it works?

推荐答案

这可能是问题,你的 check_username 控制器动作。 CakePHP的,方法是使用 JsonView 类发送任何数据丢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 看法,而是因为你没有指定或创建的它不能做到这一点。尝试改变你的行动code到这样的事情:

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';
}

另外,尽量不要在将来使用这种code建设。

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

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

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