dongmangzong8006 2016-01-13 20:36
浏览 70

Yii2 + ajax无法正常工作

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. It didnt work too(

  • 写回答

1条回答 默认 最新

  • douzhuo5671 2016-01-14 03:25
    关注

    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,
    ],
    
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用