使用escape()
,然后将它们发送到服务器之前的字符numeric character reference翻译。
从MDN escape() reference:
的十六进制形式的字符,其代码单元值为0xFF或 以下,是一个两位数转义序列:%XX。对于使用 更大的代码单位的字符,将使用四位数格式%uxxxx。
因此,很容易通过使用简单replace()
语句的escape()
输出以数字字符参考翻译:
escape(input_value).replace(/%u([0-9a-fA-F]{4})/g, '&#x$1;');
或者,如果你的服务器端语言只支持十进制实体,用途:
escape(input_value).replace(/%u([0-9a-fA-F]{4})/g, function(m0, m1) {
return '&#' + parseInt(m1, 16) + ';';
};
实施例的代码PHP
client.html
(文件编码:GB2312):
<html>
<head>
<meta charset="gb2312">
<script>
function processForm(form) {
console.log('BEFORE:', form.test.value);
form.test.value = escape(form.test.value).replace(/%u(\w{4})/g, function(m0, m1) {
return '&#' + parseInt(m1, 16) + ';';
});
console.log('AFTER:', form.test.value);
return true;
}
</script>
</head>
<body>
<form method="post" action="server.php" onsubmit="return processForm(this);">
<input type="text" name="test" value="确定">
<input type="submit">
</form>
</body>
</html>
server.php
:
<?php
echo '<script>console.log("',
$_REQUEST['test'], ' --> ',
mb_decode_numericentity($_REQUEST['test'], array(0x80, 0xffff, 0, 0xffff), 'UTF-8'),
'");</script>';
?>
不错源,我会检查出来:) – lazycai 2012-05-02 07:13:40