form提交时的字符编码转换之utf-8转gb2312 (转)

  在IE下面指定表单提交编码方式 收藏
在跨业务、跨网站发送数据或者业务升级的时候,我们有的时候需要指定发送数据的编码方式,比如页面是utf-8编码的,而发送出去的数据却希望是GB2312编码的。在做Ajax开发的时候,我们往往都是用vbscript或者用查字典法来解决这个问题(http://www.blogjava.net/emu/articles/31756.html)。但是有些业务,也许并不需要做成Ajax这么复杂,用表单提交显得更加自然。

其实html里面form标签有个accept-charset属性,可以帮助我们解决这个问题,可惜的是傻乎乎的IE浏览器虽然认得 accept-charset,却并不卖它的帐。IE的表单提交的时候使用什么编码是完全看页面的charset决定的。还好,IE在charset这个 问题上一傻到底(见http://www.blogjava.net/emu/archive/2007/08/21/138247.html),糊弄它一下,它就乖乖听话了:

view plaincopy to clipboardprint?

[c-sharp] view plaincopy
  1. <HTML>      
  2. <HEAD>      
  3.     <meta http-equiv=content-type content="text/html; charset=UTF-8">      
  4.     <SCRIPT LANGUAGE="JavaScript">      
  5.         var isIE=!!window.ActiveXObject;      
  6.         if(isIE && document.charset!="utf-8")location.reload(false);      
  7.     </SCRIPT>      
  8.     <TITLE>encode before form post</TITLE>      
  9.     <META NAME="Author" CONTENT="emu">      
  10. </HEAD>      
  11. <BODY>      
  12.     <form action="#" accept-charset="GB2312" onsubmit="if(isIE)document.charset='GB2312'">      
  13.         <input name="test" value="我" readonly>      
  14.         <input type=submit>      
  15.     </form>      
  16. </BODY>      
  17. </HTML>     


简单的讲,就是在表单发送前告诉IE说当前页面是GB2312编码就行了:
<form accept-charset="GB2312" onsubmit="if(isIE)document.charset=''GB2312''">
accept-charset="GB2312" 是写给其他没那么笨的浏览器看的。

IE为了表现它确实是一傻到底,不但在设置document.charset的时候不会用新的编码解释页面,还会在前进后退(我特地用#作为 action来实现后退)的时候又尝试用新的编码去解释页面。不过还好,可以用脚本判断出来,还可以用脚本刷新一下页面解决这个问题:
if(isIE && document.charset!="utf-8")location.reload(false);

例:提交到百度
view plaincopy to clipboardprint?

[javascript] view plaincopy
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">      
  2. <html xmlns="http://www.w3.org/1999/xhtml">      
  3. <head>      
  4. <meta name="publisher" content="TideCMS">      
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />      
  6. <title>表单提交</title>      
  7. <body>      
  8. <form action="http://www.baidu.com/s" name="f"  accept-charset="GBK"  onsubmit="document.charset='GBK'" target="_blank"><input type="text" maxlength="100" size="42" id="kw" name="wd" autocomplete="off"/> <input type="submit" id="sb" value="百度一下"/><span id="hp"><a href="/gaoji/preferences.html" mce_href="gaoji/preferences.html">设置</a><br/><a href="/gaoji/advanced.html" mce_href="gaoji/advanced.html">高级</a></span></form>      
  9. </body>      
  10. </html>     

posted on 2015-09-08 11:47  混元真人  阅读(324)  评论(0编辑  收藏  举报