我想问一下,在我通过ajax请求访问的php脚本中,我将返回json数据(从数组转换而来),如
echo json_encode($row_array);
我在jquery中获取这些数据并将其显示在表单中。在返回数据之前,我需要应用htmlspecialchars/htmlentites吗?
那么做什么才是正确的方法呢?以下代码给我一个错误:
echo htmlentities(json_encode($row_array));
谢谢你Imran
不要以这种方式应用htmlentities。您应该在json对数组进行编码并转义每个元素之前遍历数组,然后json对显示值的安全数组进行编码。在您的使用中,json只是数组的一个传输层。您显示的不是json数组,而是元素数据。不要转义传输层——这可能会使json字符串无效。
上下文很重要。
如果数据进入表单输入的value
,如果使用jQuery的val()
函数填充,则根本不需要在服务器端转义数据。
示例:http://jsfiddle.net/Y6TWv/1/
var data = '<strong>STRONG TEXT</strong>';
$('input').val(data); // output is escaped
$('p').text(data); // output is escaped
$('p').html(data); // output is not escaped
此外,如果是来逃避数据,不要这样做:
// escapes the entire json string, not good - quotes will be broken
echo htmlentities(json_encode($row_array));
在对$row_array
的每个项进行json编码之前,您必须先对其进行转义,无论是在构建数组后使用array_map
,还是在构建数组时。
一般来说,您应该更喜欢htmlspecialchars
而不是htmlentities
,但您不太可能需要任何一个。
我刚刚在JSON数组中遇到单引号问题。Chrome不喜欢在通过ajax返回的JSON响应中使用单引号。我用htmlspecialchar(,ENT_QUOTES)转义了每个值。
$theoptions['MemberList'] = array();
while($row = mssql_fetch_assoc($result)) {
$memberelement = array(
'Display'=> htmlspecialchars($row['FullName'], ENT_QUOTES),
'Value' => $row['ID']);
$theoptions['MemberList'][] = $memberelement;
}
header('Content-Type: application/json');
echo json_encode($theoptions);