在Yii 2.0中发出Ajax请求?

时间:2015-03-30 13:48:04

标签: ajax yii2

是的,我只想要一个非常简单的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;
}

EDIT ::

好的,所以这可以在这里工作。我收到弹出的警报,其中包含$ test的新值。但是我希望能够在php中访问这个值,因为最终我将从数据库访问数据,并且想要查询和做各种其他事情。

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

3 个答案:

答案 0 :(得分:7)

以下是如何访问控制器中的帖子数据:

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

答案 1 :(得分:2)

 //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>

答案 2 :(得分:1)

您可以在视图文件中包含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)
           }
        });
    }