jquery解析json数据
这是从数据库中返回数据组装的界面
json.jsp
<%@ page language="java" import="java.util.*,connection.*" pageEncoding="utf-8" contentType="text/xml"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
//得到前台传过来的数据信息与后台数据库进行比对
String content= (String)request.getAttribute("content");
List<Map.Entry<String, Integer>> contentList= new Seach(content).result();
StringBuffer sBuffer= new StringBuffer();
//sBuffer.append("[{\"name\":\"aa\"}]");
Map<String, String> jsonMap= new HashMap<String, String>();
sBuffer.append("[{");
for(int i= 0; i< contentList.size(); i++) {
if(i< contentList.size()-1){
sBuffer.append("\"name\":\""+contentList.get(i).getKey()+"\",");
}else{
sBuffer.append("\"name\":\""+contentList.get(i).getKey()+"\"}]");
}
}
request.setAttribute("json",sBuffer.toString());
%>
这是调用的servlet;
AutoComplete.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String content= request.getParameter("content");
request.setAttribute("content", content);
//使用json传递数据
request.getRequestDispatcher("json.jsp").forward(request, response);
String jsonContent= (String)request.getAttribute("json");
out.write(jsonContent.toString());
out.println(jsonContent.toString());
System.out.println(jsonContent);
out.flush();
out.close();
}
这是调用的js显示页面:
json.js
$post("AutoComplete", {content:wordText}, function(data){//成功的话进入回调函数
// var obj= "[{\"name\":\"data\",\"name\":\"ata\"}]";
var obj= data;
alert(obj.length);
var words= eval("("+obj+")");//解析每一个json元素
au.html("");
words.each(function(i) {//遍历每一个输入框并执行函数
var word= $(this);
alert(word.name);
var mouse= $("<div>").attr("id", i);
mouse.html(word.name).appendTo(au);
mouse.mouseover(function() {
if(highindex!= -1) {
au.children("div").eq(highindex)
.css("background-color", "white");
}
highindex= $(this).attr("id");
$(this).css("background-color", "gray")
});
mouse.mouseout(function() {
$(this).css("background-color", "white");
});
mouse.click(function() {//eq()获得指定位置上的jq对象
var inputContent= au.children("div").eq(highindex).text();
var inputContent= $(this).text();
highindex= -1;
au.hide();
$("#word").val(inputContent);
$("#word").focus();
});
});
if(words.length> 0) {
au.show();
}else{
au.hide();
highindex= -1;
}
},"json")
我在js上就是得不到servlet回传回来的data数据。求解