在 Yii 2.0 中发出 Ajax 请求?

Make an Ajax request in Yii 2.0?

是的,我只需要一个非常简单的 ajax 请求即可实现此功能。我是你看到的 yii 2.0 框架的新手。

在我看来index.php:

  function sendFirstCategory(){

        var test = "this is an ajax test";

        $.ajax({
            url: '<?php echo \Yii::$app->getUrlManager()->createUrl('cases/ajax') ?>',
            type: 'POST',
             data: { test: test },
             success: function(data) {
                 alert(data);

             }
         });
    }

现在,当我调用它时,我假设它应该转到我的 CasesController 以执行名为 actionAjax 的操作。

public function actionAjax()
{
    if(isset($_POST['test'])){
        $test = "Ajax Worked!";
    }else{
        $test = "Ajax failed";
    }

    return $test;
}

编辑::

好的,很好,到此为止。我取回了弹出的带有 $test 新值的警报。但是我希望能够在 php 中访问这个值,因为最终我将从数据库访问数据并且我想查询和做其他各种事情。

那么我现在如何在 php 中使用这个变量而不只是弹出警报 ()?

您可以在视图文件中以这种方式包含 js:

$script = <<< JS
    $('#el').on('click', function(e) {
        sendFirstCategory();
    });
    JS;

    $this->registerJs($script, $position);

// 其中 $position 可以是 View::POS_READY(默认值), // 或 View::POS_HEAD、View::POS_BEGIN、View::POS_END

function sendFirstCategory(){

        var test = "this is an ajax test";

        $.ajax({
           url: "<?php echo \Yii::$app->getUrlManager()->createUrl('cases/ajax') ?>",
           data: {test: test},
           success: function(data) {
               alert(data)
           }
        });
    }

以下是访问控制器中 post 数据的方法:

public function actionAjax()
{
    if(isset(Yii::$app->request->post('test'))){
        $test = "Ajax Worked!";
        // do your query stuff here
    }else{
        $test = "Ajax failed";
        // do your query stuff here
    }

    // return Json    
    return \yii\helpers\Json::encode($test);
}
 //Controller file code
public function actionAjax()
        {
            $data = Yii::$app->request->post('test');
            if (isset($data)) {
                $test = "Ajax Worked!";
            } else {
                $test = "Ajax failed";
            }
            return \yii\helpers\Json::encode($test);
        }




//_form.php code 
<script>
            $(document).ready(function () {
                $("#mausers-user_email").focusout(function () {
                    sendFirstCategory();
                });
            });

        function sendFirstCategory() {
            var test = "this is an ajax test";
            $.ajax({
                type: "POST",
                url: "<?php echo Yii::$app->getUrlManager()->createUrl('cases/ajax')  ; ?>",
                data: {test: test},
                success: function (test) {
                    alert(test);
                },
                error: function (exception) {
                    alert(exception);
                }
            })
            ;
        }
    </script>