| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2028 人关注过本帖
标题:AJAX返回中文的问题(在线等)急!!!
只看楼主 加入收藏
初心者1号
Rank: 1
等 级:新手上路
帖 子:42
专家分:0
注 册:2007-3-31
收藏
 问题点数:0 回复次数:3 
AJAX返回中文的问题(在线等)急!!!

这个是自动完成的代码,但是查中文的时候返回的是乱码!

这是JSP页面。在这里调用的SERVLET返回来的就是乱码

<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<meta HTTP-EQUIV="content-type" CONTENT="text/html; charset=UTF-8">
<title>Ajax Auto Complete</title>
<style type="text/css">

.mouseOut {
background: #708090;
color: #FFFAFA;
}

.mouseOver {
background: #FFFAFA;
color: #000000;
}
</style>
<script type="text/javascript">
var xmlHttp;
var completeDiv;
var inputField;
var nameTable;
var nameTableBody;

function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}

function initVars() {
inputField = document.getElementById("names");
nameTable = document.getElementById("name_table");
completeDiv = document.getElementById("popup");
nameTableBody = document.getElementById("name_table_body");
}

function findNames() {
initVars();
if (inputField.value.length > 0) {
createXMLHttpRequest();
var url = "autocompleteservlet?names=" + inputField.value;
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = callback;
xmlHttp.send(null);
} else {
clearNames();
}
}

function callback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
//var name = //�����������ô��д������
// xmlHttp.responseXML
// .getElementsByTagName("name")[0].firstChild.data;
//setNames(xmlHttp.responseXML.getElementsByTagName("name"));
var name = xmlHttp.responseXML.getElementsByTagName("name");
setNames(name);
//204״̬�룬no content
//û�����ĵ��������Ӧ�ü�����ʾԭ4���ĵ�
} else if (xmlHttp.status == 204){
clearNames();
}
}
}

function setNames(the_names) {
clearNames();
var size = the_names.length;
setOffsets();

var row, cell, txtNode;
for (var i = 0; i < size&& i<10; i++) { //����10���¼��ֻ��ʾǰ10��
var nextNode = the_names[i].firstChild.data;
row = document.createElement("tr");
cell = document.createElement("td");

cell.onmouseout = function() {this.className='mouseOver';};
cell.onmouseover = function() {this.className='mouseOut';};
cell.setAttribute("bgcolor", "#FFFAFA");
cell.setAttribute("border", "0");
cell.onclick = function() { populateName(this); } ;

txtNode = document.createTextNode(nextNode);
cell.appendChild(txtNode);
row.appendChild(cell);
nameTableBody.appendChild(row);
}
}

function setOffsets() {
var end = inputField.offsetWidth;
var left = calculateOffsetLeft(inputField);
var top = calculateOffsetTop(inputField) + inputField.offsetHeight;

completeDiv.style.border = "black 1px solid";
completeDiv.style.left = left + "px";
completeDiv.style.top = top + "px";
nameTable.style.width = end + "px";
}

function calculateOffsetLeft(field) {
return calculateOffset(field, "offsetLeft");
}

function calculateOffsetTop(field) {
return calculateOffset(field, "offsetTop");
}

function calculateOffset(field, attr) {
var offset = 0;
while(field) {
offset += field[attr];
field = field.offsetParent;
}
return offset;
}

function populateName(cell) {
inputField.value = cell.firstChild.nodeValue;
clearNames();
}

function clearNames() {
var ind = nameTableBody.childNodes.length;
for (var i = ind - 1; i >= 0 ; i--) {
nameTableBody.removeChild(nameTableBody.childNodes[i]);
}
completeDiv.style.border = "none";
}

</script>
</head>
<body>
<h1>Ajax Auto Complete Example</h1>
Names: <input type="text" size="20" id="names"
onblur="findNames();" style="height:20;" />
<div style="position:absolute;" id="popup">
<table id="name_table" bgcolor="#FFFAFA" border="0"
cellspacing="0" cellpadding="0"/>

<tbody id="name_table_body"></tbody>
</div>
</body>
</html>

AutoCompleteServlet是SERVLET
package newauto;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
import com.*;

public class AutoCompleteServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/xml; charset=GB2312";
private List names = new ArrayList();

public void init(ServletConfig config) throws ServletException {
names.add("Abe");
names.add("Abel");
names.add("Abigail");
names.add("Abner");
names.add("Abraham");
names.add("Marcus");
names.add("Marcy");
names.add("Marge");
names.add("Marie");
names.add("中国");
names.add("中华");
names.add("中哈哈");
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

request.setCharacterEncoding("UTF-8");
// String prefix = new String(request.getParameter("names").getBytes("ISO8859_1"),"GBK");
String prefix = StringUtil.getDecodeParamFromReq("names",request);
System.out.println(prefix);
NameService service = NameService.getInstance(names);
List matching = service.findNames(prefix);
if (matching.size() > 0) {
PrintWriter out = response.getWriter();

response.setContentType("text/xml;charset=UTF-8");
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires",0);
response.setCharacterEncoding("UTF-8");

out.println("<response>");
Iterator iter = matching.iterator();
while(iter.hasNext()) {
String name = (String) iter.next();
out.println("<name>" + name + "</name>");
out.println(name+"with name");
}
out.println("</response>");
matching = null;
service = null;
out.close();
} else { //如果结果为空,设置http状态码为204
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}

//Clean up resources
public void destroy() {
}

}


NameService是处理的JAVA
package newauto;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class NameService {
private List names;

/** Creates a new instance of NameService */
private NameService(List list_of_names) {
this.names = list_of_names;
}

public static NameService getInstance(List list_of_names) {
return new NameService(list_of_names);
}

public List findNames(String prefix) {
String prefix_upper = prefix.toUpperCase();
List matches = new ArrayList();
System.out.println(prefix);
//跟下面的一样
//for(int i=0;i<names.size();i++){

//String one_name = (String)names.get(i);

//String one_name_upper = one_name.toUpperCase();

// if(one_name_upper.startsWith(prefix_upper)){
//matches.add(one_name);
// }


Iterator iter = names.iterator();
while(iter.hasNext()) {
String name = (String) iter.next();
String name_upper_case = name.toUpperCase();
System.out.print(name +"with");
if(name_upper_case.startsWith(prefix_upper)){
boolean result = matches.add(name);
}
}
return matches;
}
}



StringUtil 这是网上找的一个转字符的类,但是用了返回也是乱码
package newauto;

import javax.servlet.http.HttpServletRequest;

public final class StringUtil {
private StringUtil() {

}

public static String getDecodeParamFromReq(String paramName,
HttpServletRequest request) {
String retval = request.getParameter(paramName);

try {
// 中间用ISO-8859-1过渡
byte[] b = retval.getBytes("8859_1");

// 转换成GB2312字符
retval = new String(b, "GB2312");
} catch (Exception e) {
e.printStackTrace();
}

return retval;
}
}


谁能帮我看看呀,已经想了很多的办法还是返回乱码。

[此贴子已经被作者于2007-11-4 17:21:28编辑过]

搜索更多相关主题的帖子: AJAX 中文 text charset 
2007-11-04 16:00
随缘小强
Rank: 1
等 级:新手上路
帖 子:23
专家分:0
注 册:2007-10-29
收藏
得分:0 
呵呵,我也在为这个问题发愁呢,不过我的是PHP的日历程序,看网上说可以在PHP里使用iconv函数转换编码,但是我转换了还是不对~

[此贴子已经被作者于2007-11-11 13:48:31编辑过]


2007-11-11 13:46
随缘小强
Rank: 1
等 级:新手上路
帖 子:23
专家分:0
注 册:2007-10-29
收藏
得分:0 

搞定了,在PHP中只要指定编码即可:header('Content-Type:text/html;charset=GB2312');
相信在你的JSP中同样也可以关于http header的注意事项我就不说了,呵呵

2007-11-12 09:09
scdmike
Rank: 1
等 级:新手上路
帖 子:24
专家分:0
注 册:2007-1-12
收藏
得分:0 
你可以在后台程序里设置编码:response.setContentType("text/xml;charset=UTF-8");

这个问题要说解决起来也很简单,原因是 Ajax 在接收 responseText 或 responseXML 的值的时候是按照 UTF-8 的格式来解码的,如果服务器端发送的数据不是 UTF-8 的格式,那么接收的值就会是乱码

你可以试一试,反正我这样做了,是没有问题的。
2007-12-05 11:08
快速回复:AJAX返回中文的问题(在线等)急!!!
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.060321 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved