通过HTML将复杂变量传递给JavaScript的正确方法 [英] Proper way to pass complex variables to javascript through HTML

查看:103
本文介绍了通过HTML将复杂变量传递给JavaScript的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图摆脱使用PHP的htmlentities,并停留在这里:

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

但是后来我想,不是替换和检查特殊字符,而只是整个对象的JSON。 p>

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

这提供了一个令人不快的结果,导致大量的双引号。
那么我应该怎么做?我应该为每个图像分配一个数字唯一标识并传递id,然后从JS数组中查找其余的数据吗?

解决方案

在这种情况下,正确的做法是:

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

htmlspecialchars 将任何双引号转换为正确的HTML转义符,使得结果字符串适用于大多数属性。 ENT_QUOTES 参数也可以处理单引号;但你可能不需要你的例子。


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.

这篇关于通过HTML将复杂变量传递给JavaScript的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆