简体   繁体   中英

How to pass yii2 search params through javascript api call

my search params is

$params=Yii::$app->request->queryParams;

And my api call is like

function doInBackground(){
      var params=<?=json_encode($params)?>;
       $.get('car/get-map-data',
          {
           "params":params
      },
      function(data){
        if(data)
        {
          console.log(data);
        }
      }); 
    }

But i am getting an error like

PHP Notice – yii\base\ErrorException
Array to string conversion

on the line

var params=<?=json_encode($params)?>;

How to solve this.I want to pass the search params to another api.

you can use getQueryString()

function doInBackground(){
  var params=<?=Yii::$app->request->getQueryString();?>;
   $.get('car/get-map-data',
      {
       "params":params
  },
  function(data){
    if(data)
    {
      console.log(data);
    }
  }); 
}

I think that handling the query params via URLSearchParams would be more non-hacky and clearer solution than obtaining them via PHP.

By URLSearchParams you can collect them into JS object and properly pass it as POST data to your AJAX request.

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