页面:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="js/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
function search() {
$.getJSON("Json", {name: "zs", age: 20}, function(json) {
$.each(json, function(i,item) {
var s = "name: " + item.name + ", age: " + item.age;
$("#output").html(s);
});
});
}
</script>
</head>
<body>
<input type="button" οnclick="search()" value="返回json"/>
<div id="output" style="width: 250px; height: 250px; border: 1px solid blue;"></div>
</body>
</html>
后台Servlet-->>Json.java:
String name = request.getParameter("name");
if(name == null) {
System.out.println("name is null");
}
String age = request.getParameter("age");
if(age == null) {
System.out.println("age is null" );
}
String json = "[{\"name\":\"ants\",\"age\": " + 20 + "},{\"name\":\"lele\",\"age\":" +30+ "}]";
response.getWriter().println(json);
后台的json字符串拼接,其对象的属性名最好带上"",之前没带上时是
"[{name:\"ants\",age: " + 20 + "},{\"name\":\"lele\",age:" +30+ "}]"一直都没有成功