我有以下代码:
echo '
<td>
<input type="button" name="delete" value="X" onclick="clearSelection(this.form, '.$type.');this.form.submit();" />
</td>'
;
问题是我不能将字符串传递给clearSelection()
Javascript 函数,因为$type
需要放在括号中。
我用反斜杠、u0222、多引号等尝试了它,但没有什么能让我找到解决方案。
解决方案:
$type = json_escape_string($type);
$raw_text = "clearSelection(this.form, $type); this.form.submit();";
$escaped_text = htmlspecialchars($raw_text);
echo '<td><input type="button" name="delete" value="X" onclick="'.$escaped_text.'" /></td>';
function json_escape_string($str){
$str = strtr($str, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/'));
return "'".$str."'";
}