1.加入jQuery.js包以及json.jar包
2.写一个实体类
public class Note implements Serializable{
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3.写一个servlet
public class LoadNoteServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
List<Note> list = new ArrayList<Note>();
Note note = new Note();
note.setId("01");
note.setName("java变量");
Note note1 = new Note();
note1.setId("02");
note1.setName("ajax应用");
list.add(note);
list.add(note1);
//将note对象集合转成json数组(静态方法)
JSONArray json = JSONArray.fromObject(list);
//out.println(json);
String json_str = json.toString();
out.print(json_str);
out.flush();
out.close();
}
}
4.在web.xml中配置servlet
<servlet>
<servlet-name>LoadNoteServlet</servlet-name>
<servlet-class>servlet.LoadNoteServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>LoadNoteServlet</servlet-name>
<url-pattern>/load.do</url-pattern>
</servlet-mapping>
5.编写load.html用于显示
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#loadNoteBtn").click(function(){
$.ajax({
url:"load.do",
type:"post",
dataType:"json",
success:function(result){
$("#note_list").empty();
for(var i=0;i<result.length;i++){
var id = result[i].id;
var name = result[i].name;
var s_li = "<li>"+name+"</li>";
var $li = $(s_li);
//藏值,将id藏到$li元素里
$li.data("noteId",id);
$("#note_list").append($li);
}
}
});
});
});
</script>
</head>
<body>
<input id="loadNoteBtn" type="button" value="显示笔记列表">
<hr>
<ul id="note_list"></ul>
</body>
</html>
6.效果