Defining the url in yii ajax get

2019-09-03 10:16发布

问题:

Am trying to perform an ajax get to a yii2 controller but the link fails to pass correctly

This is what i have tried:

$.ajax({
   url: '<?php echo Yii::$app->request->baseUrl. "/checks/items" ?>',  //this fails
   type: 'get',
   data: {
             category:category,
             _csrf : '<?=Yii::$app->request->getCsrfToken()?>'
         },
   success: function (data) {
                var parsedResult = $.parseJSON(data);
      .....
   $("#labels_trackcenter").html(html);
   }
  });

How do i pass that url

These are the config url rules:

'urlManager' => [
        'class' => 'yii\web\UrlManager',
        'enablePrettyUrl' => true,
        'showScriptName' => false,
    ],

回答1:

You can try this,take care of concatenation.

       $this->registerJs("
        $.ajax({
        url: '" . yii\helpers\Url::to(["/checks/items"]) . "',
        //OR
        url: '" . Yii::$app->urlManager->baseUrl."/checks/items',

        type: get,
        data: {
                  category:category,
                  _csrf : '" . Yii::$app->request->getCsrfToken() . "'
              },
        success: function (data) {
                     var parsedResult = $.parseJSON(data);
                      .....
                     $("#labels_trackcenter").html(html);
        }
      });
   ");


回答2:

You can use

Url::toRoute

$.ajax({
   url: '<?php echo Url::toRoute('checks/items'); ?>',  
   type: 'get',
   data: {
             category:category,
             _csrf : '<?=Yii::$app->request->getCsrfToken()?>'
         },
   success: function (data) {
                var parsedResult = $.parseJSON(data);
      .....
   $("#labels_trackcenter").html(html);
   }
  });


回答3:

Can you use Url helper class, it will change your url based on url rules which is configured in web.php file.

$.ajax({ 
   //use Url helper class for ajax url 
   url: "<?= yii\helpers\Url::to(['@web/checks/items'],true) ?>", 
   type: 'get', 
   data: { 
     category:category, 
     _csrf : "<?=Yii::$app->request->getCsrfToken()?>" 
   }, 
   success: function (data) { 
     var parsedResult = $.parseJSON(data); 
     ..... 
     $("#labels_trackcenter").html(html); 
   } 
});