在使用ajax的时候,老会遇到乱码原因。查了资料,很多解决方法,但发现,很多都不实用。后来自己用了两个方法
1-----------------------
var req = null;
var url = "。。。。。。。。。";
var post = "page=1&keyWord=中国";
if (window.XMLHttpRequest){
req = new XMLHttpRequest();
} else if(window.ActiveXObject){
req=new ActiveXObject("Microsoft.XMLHttp");
}
if(req){
req.open("POST",url,true);
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
req.send(post); //发送请求
req.onreadystatechange=function(){
if(req.readystate==4){
if(req.status==200){
document.getElementById("news_v").innerHTML=req.responseText;
} else {
alert("服务端返回状态:" + req.status + " " + req.statusText);
}
} else {
document.getElementById ("news_v").innerHTML ="数据加载中...";
}
}
}
2------------------------------------
var req = null;
var url = ".................";
var post = "page=1&keyWord=中国";
post = encodeURI(post);
post = encodeURI(post);//两次
if (window.XMLHttpRequest){
req = new XMLHttpRequest();
} else if(window.ActiveXObject){
req=new ActiveXObject("Microsoft.XMLHttp");
}
if(req){
req.open("POST",url,true);
req.setrequestheader("cache-control","no-cache");
req.setrequestheader("Content-Type","application/x-www-form-urlencoded");
req.send(post); //发送请求
req.onreadystatechange=function(){
if(req.readystate==4){
if(req.status==200){
document.getElementById("news_v").innerHTML=req.responseText;
} else {
alert("服务端返回状态:" + req.status + " " + req.statusText);
}
} else {
document.getElementById ("news_v").innerHTML ="数据加载中...";
}
}
}
我的jsp编码采用的是utf-8
其中第二种方法是别人的
比较发现,其实,他们要不是将编码指定 req.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
要不就是将字符直接编码post = encodeURI(post);
post = encodeURI(post);//两次
以上提供给大家参考