简体   繁体   中英

Proper way to pass complex variables to javascript through HTML

I was trying to get away from using PHP's htmlentities and here's where I stopped:

<?php
echo '<img ... onclick="MP.view(\''.$i->name.'\') />';
?>

But then I thought, instead of doing replaces and checks for special characters, I'll just JSON the entire object.

<?php
echo '<img ... onclick="MP.view('.json_encode($i).') />';
?>

And this provided a much undesired result putting in a ton of double quotation marks. So how should I do this? Should I assign a numerical unique id to every image and just pass the id, and then look up the rest of the data from a JS array?

The correct approach in such cases would be:

 htmlspecialchars(json_encode($var), ENT_QUOTES, "UTF-8")

htmlspecialchars turns any double quotes into the proper HTML escapes, making the resulting string suitable for most attributes. The ENT_QUOTES parameter also takes care of single quotes; but you probably don't need that in your example.

It would take a whole lot less escaping (and fewer bytes) to pass the data something like this:

echo '<script>var myObj = '.json_encode($i).'</script>';

Then, your code could look more like this:

echo '<img ... onclick="MP.view(myObj)" />';

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