尝试使用jstree json和servlet实现jstree的简单演示,但我对servlet的ajax调用不起作用必须是一个小错误但仍然无法正常工作请指导我 对此非常感激。
1)jsp页面在页面加载时调用jsp树初始化
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Chetan Jtree</title>
<link rel="stylesheet"
href="${pageContext.request.contextPath}/themes/default/style.min.css" />
<script
src="${pageContext.request.contextPath}/jquery-1.9.1.js"></script>
<script src="${pageContext.request.contextPath}/jstree.min.js"></script>
<script src="${pageContext.request.contextPath}/jtreedemo.js"></script>
</head>
<body onload="initTrees()">
<div id="jstreeloaddiv"></div>
</body>
2)编写inittree函数的js文件jtreedemo
function initTrees() {
$("#jstreeloaddiv").jstree({
"plugins" : [ "themes", "json_data", "ui" ],
"json_data" : {
"ajax" : {
"type" : "POST",
"url" : "/JSTreeDemoServlet",
"data" : function(n) {
return {
"criteria" : "get_children"
};
},
"success" : function(new_data) {
alert(new_data);
return new_data;
},
"error" : function(xhr, textStatus, errorThrown) {
alert('request failed' + textStatus);
},
"fail" : function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
}
}
});
}
3)发送json数据并且ajax调用失败的servlet。
@WebServlet("/JSTreeDemoServlet")
public class JSTreeDemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public JSTreeDemoServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println(request.getParameter("criteria"));
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
JSONArray jsonarr = new JSONArray();
JSONArray jsonarrattr = new JSONArray();
PrintWriter out= response.getWriter();
System.out.println(request.getParameter("criteria"));
for(int i =0;i<5;i++){
JSONObject jsonobj = new JSONObject();
try {
jsonarrattr = new JSONArray();
jsonobj.put("data", "Bmw"+i);
jsonarr.put(jsonobj);
jsonobj = new JSONObject();
jsonobj.put("id", i);
jsonobj.put("name", "chetan");
jsonarrattr.put(jsonobj);
jsonobj = new JSONObject();
jsonobj.put("attr", jsonarrattr);
jsonarr.put(jsonobj);
jsonobj = new JSONObject();
jsonobj.put("state", "closed");
jsonarr.put(jsonobj);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(jsonarr);
}
}
答案 0 :(得分:0)
我认为你必须使用:
$(document).ready(function(){
initTrees();
});