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.
开发者_Python百科<?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)" />';
精彩评论