在另一个问题中,有人指出,使用语义标记可以是将数据传递给onclick
函数的一种非常干净的方式,如下代码所示。
我还有第二个问题,涉及传递JSON以及让接收函数将其识别为JSON。我有一个PHP生成的JSON值[{"authed":"2012-03-04 17:24:24"},{"authed":"2012-03-04 11:44:38"}]
,需要将其传递给一个函数。直接回显到<a>
标签中是不起作用的,所以我使用urlencode()
来获得:
<a href="javascript:void(0)" data-auth="%5B%7B%22authed%22%3A%222012-03-04+17%3A24%3A24%22%7D%2C%7B%22authed%22%3A%222012-03-04+11%3A44%3A38%22%7D%5D" onclick="popup(this)">click</a>
不幸的是,当我从popup()发出警报时,我通过以下代码:
function popup(t) {
var auth = t.getAttribute('data-auth');
alert(decodeURI(auth));
}
我得到
[{"authed"%3A"2012-03-04+17%3A24%3A24"}%2C{"authed"%3A"2012-03-04+11%3A44%3A38%22"}]
JSON.parse()无法处理。关于使用此模式解码/传递JSON,有什么建议吗?
您需要使用htmlspecialchars()
来转义html——就像您在html中回显的所有一样。(你做得对吗?为了防止生成无效的html?)不要使用urlencode()
,它用于对url路径或查询参数的部分进行编码。
<?php
$data = array(array('authed'=>'2012-03-04 17:24:24'), array('authed'=>'2012-03-04 11:44:38'));
$jsondata = json_encode($data);
?>
<a data-auth="<?php echo htmlspecialchars($jsondata, ENT_COMPAT, 'UTF-8')?>" onclick="popup(this)">click</a>