如果enablePrettyUrl
设置为false
,则以下代码将按预期执行:
<?php
$script = <<< JS
$('#zip_code').change(function(){
var zipId=$(this).val();
$.get('index.php?r=locations/get-city-province',{zipId:zipId},function(data){
var data=$.parseJSON(data);
alert(data.city+" liegt in "+data.province+"! Die Id ist "+zipId);
$('#customers-city').attr('value',data.city);
$('#customers-province').attr('value',data.province);
});
});
JS;
$this->registerJS($script);
?>
以下代码不会,如果enablePrettyUrl
设置为true
:
$.get('locations/get-city-province',{zipId:zipId},function(data){
以下是UrlManager
的规则:
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => true,
'enableStrictParsing' => true,
'rules' => [
'locations' => 'locations/index',
'locations_create' => 'locations/create',
'locations_delete' => 'locations/delete',
'locations_update' => 'locations/update',
'locations_SaveAsNew' => 'locations/save-as-new',
'locations_pdf' => 'locations/pdf',
'locations_view' => 'locations/view',
// ...
],
],
任何想法,如何以正确的方式编码$.get
?
这是Controller的方法:
public function actionGetCityProvince($zipId) {
$location = Locations::findOne($zipId);
echo Json::encode($location);
}
答案 0 :(得分:1)
<?php
$url = yii\helpers\Url::to(['locations/get-city-province']);
$script = <<< JS
$('#zip_code').change(function(){
var zipId = $(this).val();
$.get('$url', {zipId:zipId}, function(data){
var data = $.parseJSON(data);
alert(data.city+" liegt in "+data.province+"! Die Id ist "+zipId);
$('#customers-city').attr('value',data.city);
$('#customers-province').attr('value',data.province);
});
});
JS;
$this->registerJS($script);
?>