p48 Ajax 处理JSON对象
做跟json相关的,需要引入一大堆的包
JsonServlet.java
package org.lanqiao.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.lanqiao.entity.Student;
import net.sf.json.JSONObject;
/**
* Servlet implementation class JsonServlet
*/
public class JsonServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
Student stu1 = new Student();
stu1.setAge(23);
stu1.setName("zs");
Student stu2 = new Student();
stu1.setAge(33);
stu1.setName("second");
Student stu3 = new Student();
stu1.setAge(44);
stu1.setName("trois");
JSONObject json = new JSONObject();
json.put("stu1", stu1);
json.put("stu2", stu2);
json.put("stu3", stu3);
out.print(json); //返回Json对象 {"stu1":stu1, "stu2":stu2, "stu3":stu3}
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
index6.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.bootcss.com/jquery/1.10.0/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function register()
{
var $mobile = $("#mobile").val();
$("#tip").load(
"MobileServlet",
"mobile="+$mobile
);
}
/*Json中只有一个对象的情况
function testJson()
{
var $mobile = $("#mobile").val();
$.post(
"JsonServlet",
//"mobile="+$mobile,
{"name":"zs","age":24},
function(result)
{
//js需要通过eval()函数,将返回值转为,一个js能够识别的对象
var jsonStudent = eval(result.stu1);
}
);
}
*/
//Json中有多个对象的情况
function testJson()
{
$.getJSON(
"JsonServlet",
//"mobile="+$mobile,
{"name":"zs","age":24},
function(result)
{
//result:{"stu1":stu1, "stu2":stu2, "stu3":stu3}
//js需要通过eval()函数,将返回值转为,一个js能够识别的对象
var json = eval(result);
alert("json:"+json);
$.each(json,function(i,element){
alert(this.name+"---"+this.age);
});
}
);
}
</script>
</head>
<body>
手机:<input id="mobile"/>
<br/>
<input type="button" value="注册" onclick="register()"/>
<span id="tip"></span>
<input type="button" value="测试json" onclick="testJson()"/>
</body>
</html>
Student.java
package org.lanqiao.entity;
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}