ajax 可能是乱码问题引起的

ai_ziji1413 2011-07-20 06:39:50
Action 中拼了一个xml格式的字符串:
StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?> <RoutePlace>");
HttpSession session = request.getSession(false);
List list = dao.getRootFlag();
for(int i=0;i<list.size();i++){
RoutePlace rp = (RoutePlace)list.get(i);
sb.append("<place>");
sb.append("<porder>"+rp.getPorder()+"</porder>");
sb.append("<lon>"+rp.getLon()+"</lon>");
sb.append("<lat>"+rp.getLat()+"</lat>");
sb.append("<areaID>"+rp.getAreaID()+"</areaID>");
sb.append("<name>" + "汉字" + "</name>");
sb.append("</place>");
}
sb.append("</RoutePlace>");

PrintStream out = new PrintStream(response.getOutputStream());
out.println(sb);


jsp页面:
function send_request(url,type){
var http_request=false;//初始化变量
if(window.XMLHttpRequest){
http_request = new XMLHttpRequest();
if(http_request.overrideMimeType){
http_request.overrideMimeType("text/xml");
}
}else if(window.ActiveXObject){
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
if(!http_request){
window.alert("不能创建XMLHttpRequest对象实例!");
return false;
}
http_request.open("GET",url,true);
http_request.send(null);

function processRequest(){
if(http_request.readyState==4){
if(http_request.status==200){
var xmlDoc=http_request.responseXML;
window.alert(xmlDoc.xml);
var thePlace = xmlDoc.getElementsByTagName("place");
window.alert("== " + thePlace.length);
for(var i=0;i<thePlace.length;i++){ }
}
}
}

}


问题描述:
Action中的 :sb.append("<name>" + "汉字" + "</name>");
若换成 sb.append("<name>" + "test" + "</name>");
整个过程获取xml文件都没问题,可是一旦出现中文,就没有了结果。
如果无中文出现:
window.alert(xmlDoc.xml);
window.alert("== " + thePlace.length);
两个alert 都没有问题,能输出正确的值。
如果出现了中文:
window.alert(xmlDoc.xml); alert 空白
window.alert("== " + thePlace.length); alert 出 长度为0(其实正确的结果不应该为0);

诸位给出出注意,看问题出在了哪里,难道是乱码引起的,该怎么处理?

...全文
75 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
lsw645645645 2011-07-21
  • 打赏
  • 举报
回复
看看返回的数据是什么嘛
孟子E章 2011-07-21
  • 打赏
  • 举报
回复
应该是编码导致的,注意不是乱码,你应该对Action 返回utf-8格式的内容
ai_ziji1413 2011-07-21
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 lsw645645645 的回复:]
看看返回的数据是什么嘛
[/Quote]
都说啦,在全英文的情况况下,什么都是正确的,只有在出现中文的情况下才会 出现回调函数失败
ai_ziji1413 2011-07-21
  • 打赏
  • 举报
回复
PrintStream out = new PrintStream(response.getOutputStream());
改写成:
PrintStream out = new PrintStream(response.getOutputStream(),false,"utf-8");

另是没贴出的部分:
response.setContentType("text/xml");
改为
response.setContentType("text/xml;charset=utf-8");

问题解决
ai_ziji1413 2011-07-20
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 xiaowushen 的回复:]

建议编码中文再用var xmlDoc=http_request.responseXML; 获取
[/Quote]
能具体点么
路过的码农 2011-07-20
  • 打赏
  • 举报
回复
建议编码中文再用var xmlDoc=http_request.responseXML; 获取

52,797

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 Ajax
社区管理员
  • Ajax
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧