Welcome 微信登录

首页 / 脚本样式 / JavaScript / 表单数据提交时的字符编码问题

表单数据提交时的字符编码问题2010-01-03人老了,以前研究过的东西都忘记了。所以还是记录下来比较好。

废话不说,翠花,上代码:

Html代码

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>The Character Encoding for Form Submission</title>
<script>
function $(id) {
return document.getElementById(id)
}
function createPropertyEditor(name) {
var p = document.createElement("p")
p.appendChild(document.createTextNode(name + " = "))
var input = document.createElement("input")
input.type = "text"
var get = new Function("this.value = String($name); this.select()".replace(/$name/g, name))
get.call(input)
input.onfocus = get
input.onchange = new Function("
try {
$name = this.value
} catch(e) {
alert(e.message)
} finally {
this.value = String($name)
}
".replace(/$name/g, name))
p.appendChild(input)
$("properties").appendChild(p)
}
var form
window.onload = function () {
form = document.forms[0]
createPropertyEditor("document.charset")
createPropertyEditor("document.defaultCharset")
createPropertyEditor("document.characterSet")
createPropertyEditor("document.inputEncoding")
createPropertyEditor("document.xmlEncoding")
//createPropertyEditor("document.mimeType")
createPropertyEditor("form.acceptCharset")
createPropertyEditor("form.method")
createPropertyEditor("form.enctype")
//createPropertyEditor("form.encoding")
}
</script>
</head>
<body>
<form>
<input name="_charset_" type="hidden">
<input name="test" type="text" value="&#31616;&#20307;-&#32321;&#39636;-English">
<input type="submit">
<div id="properties"></div>
</form>
</body>
</html>
如果你总是使用utf-8编码,则基本不用为编码问题伤脑筋。但是总有些时候,事情超出了你的掌控范围。

通常表单提交时将按照文档本身的编码进行编码。如果是一个gb2312的文档,如何按照utf-8编码提交呢?此外是否可以通知服务器,请求是按照何种方式编码的呢?

以上代码测试了浏览器为此类问题所提供的各种特性。可将上述代码保存为不同的编码,如UTF-8、GB2312、Big5等(可以加上meta httpequiv=content-type content=text/html;charset=xxx),然后进行测试(即修改document.charset和form.acceptCharset然后提交,观察URL参数的结果)。

以下是一些浏览器的测试结果(仅测试了GET请求):

Text代码

支持document.charset 支持form.acceptCharset 支持_charset_

IE6 Y N* Y
FF2 N Y Y
Safari3 Y Y N
Chrome1 Y Y N
Opera9 N* Y Y