将数据从javascript发送到控制器Yii


Sending data from javascript to Controller Yii

我正试图将一个数组从Yii的控制器发送到一个动作,但我一直得到404。这就是我从javascript发送数据的方式:

$.ajax({
    url: baseUrl + '/user/validateUser',
    data: $('#usr').val(),
    type: 'post',
    dataType: 'json',
    success: function(res)
    {
        console.log(res);
    }
});

在我的UserController中,我有以下动作:

public function actionValidateUser() {
    if ($_POST > 0){
        $username = $_POST['username'];
        var_dump($username);
    }
}

我得到这样的响应:

Request URL:http://localhost/myapp/user/validateUser
Request Method:POST
Status Code:404 Not Found

我做错了什么?在Zend我这样做了,它工作得很好。在这里……我不知道。

似乎你的apache重写规则不正确/不存在。在htdocs文件夹下创建/编辑名为.htaccess的文件。输入以下内容:

Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php

保存并重启apache。确保在apache httpd.conf中启用了mod_rewrite

您的ajax调用接收一个字符串作为数据,并且没有关于该字符串表示哪个字段的信息。您应该指明该数据代表哪个字段。

试试下面的代码:

$.ajax({
    url: baseUrl + '/user/validateUser',
    data: { username: $('#usr').val() },
    type: 'post',
    dataType: 'json',
    success: function(res)
    {
        console.log(res);
    }
});

你的原始请求正在生成一些调用//localhost/myapp/user/validateUser?<<em>username>。但是上面的代码将生成对//localhost/myapp/user/validateUser的调用?username=<<em>username>