简体   繁体   中英

Escape quotes when building javascript from php

Basically, I'm taking user input and passing it to a javascript function in a page from php. But because the user use's apostrophes, I'm getting errors. What's the proper escape function in php to use on a variable that will be surrounded by quotes. IE:

Some php:

$userString = "Joe's Pizza";
// escape here
echo "<script type=\"text/javascript\">myFunction('$userString');</script>";

Thanks much!

Wrap it in an object/associative array and use json_encode .

$array = array('data' => $userString);
$encoded_array = json_encode($array);
echo "<script type=\"text/javascript\">myFunction($encoded_array);</script>";

myFunction could look like:

function myFunction(obj)
{
  var data = obj.data;
  ... 
}

This also allows you to easily make the object more complex if needed.

addslashes ; eg

$userString = addslashes("Joe's Pizza");
print '<script type="text/javascript">myFunction('$userString');</script>";;

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