使用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