我是ajax初学者。我试图写一个简单的搜索建议。当我使用firefox测试它工作,但当我使用chrome我得到了:未捕获TypeError:无法读取属性' getElementsByTagName'为null
我在回调函数
上写了这个xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = xhr.responseXML;
var x = data.getElementsByTagName("suggestion");
var div = document.getElementById("suggest")
div.innerHTML = "";
showSuggest();
for (var i = 0; i < x.length; i++) {
var result= x[i].firstChild.nodeValue;
div.innerHTML += "<div id='sResult' onmouseover='over(this)' onmouseout='out(this)' onclick='replace(this)' >"
+ result+ "</div>";
}
}
}
和Servlet doGet方法:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("test/xml;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
String keyword = request.getParameter("keyword");
//get suggestion from db
List<KeyWord> kw = SearchService.suggest(keyword);
PrintWriter pw = response.getWriter();
pw.println("<?xml version='1.0' encoding='UTF-8'?>");
pw.write("<suggestions>");
for(KeyWord k:kw){
pw.write("<suggestion>");
pw.write(k.getContent());
pw.write("</suggestion>");
}
pw.write("</suggestions>");
pw.flush();
pw.close();
}
答案 0 :(得分:0)
如果您的帖子中response.setContentType("test/xml;charset=UTF-8");
不是拼写错误,请将其更正为response.setContentType("text/xml;charset=UTF-8");
,并希望IE和Chrome填充responseXML
。
答案 1 :(得分:-1)
你试过这个吗?
var x = data.documentElement.getElementsByTagName("suggestion");
而不是
var x = data.getElementsByTagName("suggestion");