简体   繁体   中英

Concatenation of php variable with javascript

var settings = {
  "async": true,
  "crossDomain": true,
  "url": 'https://example.com/something.aspx?i='<? echo urlencode($_GET['id']); ?>,
  "method": "GET",
  "headers": {
    "cache-control": "no-cache",
  }
}

It doesn't work this way, the concatenation is wrong I think. Tried few ways still doesn't work.

You need to put the data inside the JavaScript string literal. Move the ' to after the extra data you are outputting.

You just had the single quote the wrong side.

Don't forget you're outputting to HTML, so you don't have to concatenate a PHP variable to a JavaScript variable.

var settings = {
  "async": true,
  "crossDomain": true,
  "url": 'https://example.com/something.aspx?i=<?php echo urlencode($_GET['id']); ?>',
  "method": "GET",
  "headers": {
    "cache-control": "no-cache",
  }
}

Maybe you can try it the other way round. Like

<?php
  echo 'var settings = {
    "async": true,
    "crossDomain": true,
    "url": "https://example.com/something.aspx?i='.urlencode($_GET['id']).'",
    "method": "GET",
    "headers": {
      "cache-control": "no-cache",
    }
  }'; 
?>

Please note the changes I made with the ' and " in the url attribute.

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