URL编码在Yi2和jQuery中不起作用

URL编码在Yi2和jQuery中不起作用,jquery,yii2,Jquery,Yii2,我正在使用Yi2框架,并使用jQuery$.post()方法从URL获取数据。 从jQuery发送的URL如下所示: http://localhost/basic/web/index.php?r=visitor%2Fcenter%26location_id%3D6 c_center4 c_center3 c_center2 c_center1 给出了404页面未找到错误 同时,当我使用&和=,从浏览器中使用以下URL时 http://localhost/basic/web/index.php

我正在使用Yi2框架,并使用jQuery
$.post()
方法从URL获取数据。 从jQuery发送的URL如下所示:

http://localhost/basic/web/index.php?r=visitor%2Fcenter%26location_id%3D6
c_center4
c_center3
c_center2
c_center1
给出了
404页面未找到错误

同时,当我使用&和=,从浏览器中使用以下URL时

http://localhost/basic/web/index.php?r=visitor%2Fcenter&location_id=6
我可以得到如下结果:

http://localhost/basic/web/index.php?r=visitor%2Fcenter%26location_id%3D6
c_center4
c_center3
c_center2
c_center1
视图中的jQuery代码如下所示

[
         'onchange' => '
                console.log("'.Yii::$app->urlManager->createUrl('visitor/center&location_id=').'" +$(this).val());
                $.post( "'.Yii::$app->urlManager->createUrl('visitor/center&location_id=').'"+$(this).val(), function( data ) {
                  $( "select#visitor_center" ).html( data );
                });
        ']
我想不出原因。
提前感谢。

您不应该以这种方式传递查询字符串。如果您将字符串传递给
createUrl()
,它将被视为路由,所有特殊字符都将被编码(因为
visitor/center&location\u id=
应被视为
r
param的值,因此需要对其进行编码)

您可以尝试以下方法:

[
    'onchange' => '
        $url = "' . Yii::$app->urlManager->createUrl(['visitor/center', 'location_id' => '']) . '" + $(this).val(); 
        console.log($url);',
]

这应该可以单独生成route和param,而不需要不必要的编码。

我试过了。但是代码
'onchange'=>'$url=Yii::$app->urlManager->createURL(['visitor/center','location\u id'=>'100']);console.log($url);'
给出了
语法错误,意外的“访问者”(T_字符串),应为“]”
您的引用不正确,请尝试
'onchange'=>'$url=“”。Yii::$app->urlManager->createUrl(['visitor/center','location_id'=>'100']);console.log($url);'非常感谢。我在想这个。但是有点和引号混淆了。请帮助我,我不想硬编码100,它将是函数的输入,所以我需要
$(this).val()
,而不是100。我正在努力,但没有用。Quoates让我很困惑。在我的回答示例中,没有硬编码的值,有空字符串作为param值,所以您应该能够在JS中的URL末尾附加ID。