我正在使用servlet和ajax来传递数据,但是,servlet返回的xml文件总是等于' Null'而且我无法弄明白为什么!
这是我处理数据的Servlet函数:
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
// Set response content type
response.setContentType("text/xml");
PrintWriter out = response.getWriter();
String action = request.getParameter("action");
String searchQuery = request.getParameter("q");
//String searchQuery = request.getParameter("query");
StringBuffer sb = new StringBuffer();
boolean change = false;
if(searchQuery != null){
//remove spaces and convert to lower case
searchQuery = searchQuery.trim().toLowerCase();
}
if(action.equals("complete")){
// check if user sent empty string
if (!searchQuery.equals("")) {
for (String key : comp.keySet()) {
if (comp.get(key).startsWith(searchQuery)){
sb.append("<result>");
sb.append("<id>" + comp.get(key) + "</id>");
sb.append("</result>");
change = true;
}
}
}
}
if (change) {
response.setHeader("Cache-Control", "no-cache");
out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
out.write("<results>" + sb.toString() + "</results>");
} else {
//indicating that the request succeeded but that there was no new information to return.
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
}
这是我收到请求的地方:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
parseMessages(xhttp.responseXML);
}
}
parseMessages中的代码抛出错误,因为我尝试调用null参数。 任何帮助将不胜感激!