ie ajax乱码解决方案

Life is short , play more!
本文来自lihao's Blog,转载请注明。

Ajax技术的核心为Javascript,而javascript使用的是UTF-8编码,因此在页面采用GBK或者其他编码,同时没有进行编码转换时,就会出现中文乱码的问题。以下是分别使用GET和POST方式传值,并且页面采用GBK和UTF-8编码在IE和FF下的不同测试结果和出现乱码时的解决方案表, 见下面.

关于encodeURI, encodeURIComponent, escape的区别.

escape()

Don’t use it, as it has been deprecated since ECMAScript v3. 不要使用了.

encodeURI()

Use encodeURI when you want a working URL. Make this call:

使用encodeURI 那么你的期望结果是:

encodeURI("http://www.google.com/a file with spaces.html")

to get: 运行后,得到的结果是

http://www.google.com/a%20file%20with%20spaces.html

Don’t call encodeURIComponent since it would destroy the URL and return

不要调用encodeURIComponent, 因为它会破坏你的url. 看下面的时encodeURIComponent地返回.

http%3A%2F%2Fwww.google.com%2Fa%20file%20with%20spaces.html

encodeURIComponent()

Use encodeURIComponent when you want to encode a URL parameter.

只是在去encode url的参数时, 针对url 切勿使用!!!

param1 = encodeURIComponent("http://xyz.com/?a=12&b=55")

Then you may create the URL you need:

url = "http://domain.com/?param1=" + param1 + "&param2=99";

And you will get this complete URL:

http://www.domain.com/?param1=http%3A%2F%2Fxyz.com%2F%Ffa%3D12%26b%3D55&param2=99

Note that encodeURIComponent does not escape the ‘ character. A common bug is to use it to create html attributes such as href='MyUrl', which could suffer an injection bug. If you are constructing html from strings, either use ” instead of ‘ for attribute quotes, or add an extra layer of encoding (‘ can be encoded as %27).

 

传值方式 客户端编码 服务器端编码 IE FF 解决方案
GET UTF-8 UTF-8 接收$_GET传递的参数时出现乱码 正常 客户端url=encodeURI(url)
GET GBK GBK 正常 接收$_GET传递的参数时出现乱码 客户端url=encodeURI(url)
服务器端
$str=iconv(“UTF-8″,”GBK”,$str)
POST UTF-8 UTF-8 接收$_GET传递的参数时出现乱码 正常 客户端url=encodeURI(url)
POST UTF-8 UTF-8 接收$_POST传递的参数时正常 接收$_POST传递的参数时正常 推荐采用方式
POST GBK GBK 正常 接收$_GET传递的参数时出现乱码 客户端url=encodeURI(url)
服务器端
$str=iconv(“UTF-8″,”GBK”,$str)
POST GBK GBK 接收$_POST传递的参数时出现乱码 接收$_POST传递的参数时出现乱码 服务器端
$str=iconv(“UTF-8″,”GBK”,$str)

 

参考文档

http://blog.csdn.net/fanteathy/article/details/7362105

http://www.jb51.net/article/24097.htm

http://stackoverflow.com/questions/75980/best-practice-escape-or-encodeuri-encodeuricomponent


发表评论

电子邮件地址不会被公开。 必填项已用*标注