使用escape()
然后将字符转换为数字字符引用,然后再将它们发送到服务器。
来自MDN escape() 参考:
字符的十六进制形式,其代码单元值为 0xFF 或更小,是两位转义序列:%xx。对于具有更大代码单元的字符,使用四位数格式 %uxxxx。
因此,很容易通过使用一个简单的语句将输出转换escape()
为数字字符引用:replace()
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>';
?>