有一种解决办法就是使用encodeURIComponent加上修改
Content-Type
为
application/x-www-form-urlencoded"
来把数据统一编码成
url
格式,当然,也可以指定编码,如:“application/x-www-form-urlencoded
charset=utf-8
”,
解决方法之一
例子:
复制代码
代码如下:
http_request
=
new
ActiveXObject("Msxml2.XMLHTTP")
http_request.setrequestheader("content-type","application/x-www-form-urlencoded
charset=utf-8")
解决方法之二
就是在PHP文件中显示声明为GB2312
复制代码
代码如下:
header("Content-Type:text/htmlcharset=GB2312")
而对于发送到服务器的中文进行转码.
如下
复制代码
代码如下:
<?php
header("Content-Type:text/htmlcharset=GB2312")
if($_POST['content'])
{
$_POST["content"]=iconv("UTF-8","gb2312",$_POST["content"])
print("内容是".$_POST['content'])
}
else
{
print("没有内容发送")
}
?>
因而这样可以解决乱码问题
jsp中ajax中文乱码
发送路径中的参数有中文,在服务器段接收参数值是乱码
例如:
var
url="a.jsp?name=小李";
xmlHTTP.open
("post",url,true)
解决办法:
利用javascript的提供的escape()或encodeURI()方法
例如:
客户端:
复制代码
代码如下:
var
url="a.jsp?name=小李";
url=encodeURI(url)
url=encodeURI(url)
//两次,很关键[具体为什么,我也不清楚]
/********************************************/
也有人写成var
url="a.jsp?name=escape("小李")";
功能和encodeURI方法类似。
复制代码
代码如下:
/********************************************/
xmlHTTP.setrequestheader("cache-control","no-cache")
xmlHTTP.setrequestheader("Content-Type","application/x-www-form-urlencoded")
xmlHTTP.setrequestheader("contentType","text/htmlcharset=uft-8")//指定发送数据的编码格式
xmlHTTP.open
("post",url,true)
服务器端:
复制代码
代码如下:
String
name
=
request.getParameter("name")
name
=
java.net.URLDecoder.decode("name",
"UTF-8")
2)返回来的responseText或responseXML的值中含有中文是乱码
原因:AJAX在接收responseText或responseXML的值的时候是按照UTF-8的格式来解码的,如果服务器段发送的数据不是UTF-8的格式,那么接收responseText或responseXML的值有可能为乱码。
解决办法:在服务器指定发送数据的格式:
在jsp文件中:
response.setContentType("text/textcharset=UTF-8")//返回的是txt文本文件
或是
response.setContentType("text/xmlcharset=UTF-8")//返回的xml文件
gb2312
jquery
ajax
获取数据
gb2312
是
jsp:<%@page
contentType="application/json"
pageEncoding="gb2312"%>这里用的json作测试,与text/html应该一样
aps:Response.Charset="gb2312"(参照网络未测试)
php:header("Content-Type:text/html
charset=gb2312")(参照网络未测试)
html:未解决
gb2312
jquery
ajax
获取数据
utf-8
否
utf-8
jquery
ajax
获取数据
utf-8
否
utf-8
jquery
ajax
获取数据
gb2312
是
jsp:<%@page
contentType="application/json"
pageEncoding="gb2312"%>这里用的json作测试,与text/html应该一样
aps:Response.Charset="gb2312"(参照网络未测试)
php:header("Content-Type:text/html
charset=gb2312")(参照网络未测试)
html:未解决
ajax中文乱码解决办法:在jquery-1.6.1文件中,搜索’contentType’
然后在application/x-www-form-urlencoded后面加上charset=UTF-8
最终变成contentType:”application/x-www-form-urlencodedcharset=UTF-8”即可。
这样通过post方法提交后会出现乱码的问题就可以完美解决。
1、前后台编码要统一; 2、在使用gb2312编码时,不要用jquery的$.get()或$.post()做ajax提交,因为这两个方法默认为utf-83、用$.ajax()并在其中加入:contentType:"pplication/x-www-form-urlencodedcharset=GB2312"写成以下形式