简体   繁体   中英

Yii2 + ajax not working

I tried use answers about yii and ajax but not finded working examle. My script in yii2 bacis views/site/about.php:

<script>
    function myFunction()
    {
        $.ajax({
            url: '<?php echo Yii::$app->request->baseUrl . '/controllers/SiteController/sample' ?>',
            type: 'post',
            data: {
                searchname: 10,
                searchby: 25,
                _csrf: '<?= Yii::$app->request->getCsrfToken() ?>'
            },
            success: function (data) {
                console.log(data.search);
                console.log(data.code);
            }
        });

    }
</script>

My function in SiteController:

   public function actionSample() {

        if (Yii::$app->request->isAjax) {

            $search = "some-string";
            $code = 20;
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return [
                'search' => $search,
                'code' => $code,
            ];
        }
    }

I see post from ajax in browser OK.

 POST http://localhost/web/controllers/SiteController/sample    
    200 OK

But conroller not answer . I get: "undefined". May be problems with url? But I tried other: Yii::$app->request->baseUrl . '/controllers/sample Yii::$app->request->baseUrl . '/controllers/sample . It didnt work too(

You should use /site/sample instead or just sample if view belongs to action of SiteController :

$.ajax({
    url: '/site/sample',
    ...
});

Also placing JavaScript inside of script tag in view is not welcomed in Yii. You should use at least registerJs or registerJsFile or assets (recommended). There are dedicated sections about assets and client scripts in official guide.

Also make sure that your server configured to access web/index.php for correct work.

Update: We investigated problem deeper and the reason was the pretty urls were not enabled. Adding this to application config solved the problem:

'urlManager' => [
    'showScriptName' => false,
    'enablePrettyUrl' => true,
],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM