Ajax中文传参出现乱码

      Ajax技术的核心为Javascript,而javascript使用的是UTF-8编码,因此在页面采用GBK或者其他编码,同时没有进行编码转换时,就会出现中文乱码的问题。

      以下是分别使用GET和POST方式传值,并且页面采用GBK和UTF-8编码在IE和FF下的不同测试结果和出现乱码时的解决方案。

传值方式 客户端编码 服务器端编码 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)

       另在IE中可能存在这样一个问题:由于出现错误c00ce56e而导致此项操作无法完成。

      此时设置编码时将header('Content-Type:text/html;charset=utf8')改为header('Content-Type:text/html;charset=utf-8')即可。

开发中所遇实例:

通过Jquery的$.get()方法传中文参数,后台接收,页面编码未设置,FireFox下正常,IE下乱码

var name = "中国";
var url = "/Movies/GetMovieName?name=" + name;
$.get(url,{}, function () {}, "json");

解决方法:

[1]Js请求时进行二次编码:url=encodeURI(url); url=encodeURI(url); //即url=encodeURI(encodeURI(url));

var name = encodeURI(encodeURI("中国")); 
var url = "/Movies/GetMovieName?name=" + name;
$.get(url,{}, function () {}, "json")

[2]解码

(1)C#后台解码:

public void GetMovieName(string name)
{
    //HttpUtility.UrlDecode 方法
    name = System.Web.HttpUtility.UrlDecode(name);
    //Server.UrlDecode 方法
    name = Server.UrlDecode(name);  
}

(2)JS解码:decodeURI(url);

注:JS、C#编码解码如下:

escape不编码字符有69个:*,+,-,.,/,@,_,0-9,a-z,A-Z

encodeURI不编码字符有82个:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z

encodeURIComponent不编码字符有71个:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z

[1]、JS: escape(name) :

js使用数据时可以使用escape。

例如:搜藏中history纪录。

0-255以外的unicode值进行编码时输出%u****格式,其它情况下escape,encodeURI,encodeURIComponent编码结果相同。

(1)JS解码:unescape(name);

(2)C#:HttpUtility.UrlEncode()   HttpUtility.UrlDecode();

[2]、JS: encodeURI():

进行url跳转时可以整体使用encodeURI()

例如:Location.href=encodeURI("http://cang.baidu.com/do/s?word=百度&ct=21");

(1)JS解码:decodeURI();

(2)C#解码: decodeURIComponent();

[3]、JS: encodeURIComponent():

传递参数时需要使用encodeURIComponent,这样组合的url才不会被#等特殊字符截断。                           

例如:<script language="javascript">document.write('<a href="http://passport.baidu.com/?logout&aid=7& u='+encodeURIComponent("http://cang.baidu.com/bruce42")+'">退出</a& gt;');</script>

(1)解码使用decodeURIComponent(u);

(2)C#:[HttpContext.Current.]Server.UrlDecode(url)    [HttpContext.Current.]Server.UrlEncode(url);

posted on 2014-11-10 11:02  Now,DayBreak  阅读(1652)  评论(0编辑  收藏  举报