jquery异步传输方式:
①返回html类型的数据
jsp代码如下:
- <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="js/jquery-1.8.1.js"></script>
<script type="text/javascript">
$(function(){
$("#button1").click(function(){
$.ajax({
type:"post",
url:"MyServlet",
dateType:"html",
data:{'param1':$("#param1").val(), 'param2':$("#param2").val()},
success:function(returnedData){
$("#result").attr("value",returnedData);
}
});
});
});
</script>
<body>
<input type="text" id="param1" size="5"> +
<input type="text" id="param2" size="5">
<input type="button" value="sum" id="button1">
<input type="text" id="result" size = "5">
</body>
</html>
MyServlet代码如下:
package com.json.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;
public class MyServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//在前台控制输入只能为数字
int param1 = Integer.parseInt(req.getParameter("param1"));
int param2 = Integer.parseInt(req.getParameter("param2"));
resp.setContentType("text/html;charset=utf-8");
PrintWriter pw = resp.getWriter();
pw.print(String.valueOf(param1+param2));
pw.flush();
}
}
②返回xml数据(ajax和post两种不同方式,post方式底层也是调用ajax)需要添加dom4j.jar包
jsp代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="js/jquery-1.8.1.js"></script>
<script type="text/javascript">
$(function(){
$("#button1").click(function(){
/*$.ajax({
type:"post",
url:"XMLServlet",
dataType:"xml",
data:{'name':$("#name").val()},
success:function(returnData){
var id = $(returnData).find("id").text();
var name = $(returnData).find("name").text();
var age = $(returnData).find("age").text();
var address = $(returnData).find("address").text();
$("#theBody table:eq(0)").remove();
var html = "<table width='60%' border='1' align='center'><tr><th>id</th><th>name</th><th>age</th><th>address</th><tr align='center'><td>"+id+"</td><td>"+name+"</td><td>"+age+"</td><td>"+address+"</td></tr></table>";
$("#theBody").append(html);
}
});*/
$.post("XMLServlet",{
name:$("#name").val()
},function(returnData,status){
var id = $(returnData).find("id").text();
var name = $(returnData).find("name").text();
var age = $(returnData).find("age").text();
var address = $(returnData).find("address").text();
$("#theBody table:eq(0)").remove();
var html = "<table width='60%' border='1' align='center'><tr><th>id</th><th>name</th><th>age</th><th>address</th><tr align='center'><td>"+id+"</td><td>"+name+"</td><td>"+age+"</td><td>"+address+"</td></tr></table>";
$("#theBody").append(html);
}
);
});
});
</script>
<body id="theBody">
<select id="name">
<option value="zhangsan">zhangsan</option>
<option value="lisi">lisi</option>
</select>
<input type="button" id="button1" value="get context from server">
</body>
</html>
XMLServlet代码如下:
package com.json.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.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import com.json.dto.Person;
public class XMLServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getParameter("name");
Person person = new Person();
if("zhangsan".equals(name))
{
person.setId(1);
person.setName("zhangsan");
person.setAddress("beijing");
person.setAge(30);
}else
{
person.setId(2);
person.setName("lisi");
person.setAddress("shanghai");
person.setAge(20);
}
Document document = DocumentHelper.createDocument();
Element rootElement = document.addElement("users");
rootElement.addComment("This s a comment!");
Element userElement = rootElement.addElement("user");
Element idElement = userElement.addElement("id");
Element nameElement = userElement.addElement("name");
Element ageElement = userElement.addElement("age");
Element addressElement = userElement.addElement("address");
idElement.setText(person.getId()+"");
nameElement.setText(person.getName());
ageElement.setText(person.getAge()+"");
addressElement.setText(person.getAddress());
resp.setContentType("text/xml; charset=utf-8");
//浏览器无缓存
resp.setHeader("pragma", "no-cache");
resp.setHeader("cache-control", "no cache");
PrintWriter out = resp.getWriter();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter xmlWriter = new XMLWriter(out, format);
xmlWriter.write(document);
out.flush();
}
}
所使用到的Person代码如下:
package com.json.dto;
public class Person {
private int id;
private String name;
private int age;
private String address;
public Person(int id, String name, int age, String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
public Person() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
③json数据形式(需要导入gson.jar包)
jsp代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="js/jquery-1.8.1.js"></script>
<script type="text/javascript">
$(function(){
$("#button1").click(function(){
$.ajax({
type:"post",
url:"JsonServlet",
dataType:"json",
data:{},
success:function(returnData){
var html="<table align='center' width='60%' border='1'><tr><th>id</th><th>name</th><th>homeAddress</th><th>companyAddress</th></tr>";
for(var i = 0; i < returnData.length; i++)
{
var people = returnData[i];
var id = people.id;
var name = people.name;
var companyAddress = people.address.companyAddress;
var homeAddress = people.address.homeAddress;
html += "<tr align='center'><td>"+id+"</td><td>"+name+"</td><td>"+companyAddress+"</td><td>"+homeAddress+"</td></tr>"
}
html += "</table>";
$("#tbody table:eq(0)").remove();
$("#tbody").append(html);
}
});
});
});
</script>
<body id="tbody">
<input type="button" value="get json from server" id="button1">
</body>
</html>
JsonServlet代码如下:
package com.json.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.json.dto.Address;
import com.json.dto.People;
public class JsonServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
List<People> list = new ArrayList<People>();
People people1 = new People();
Address address1 = new Address();
address1.setHomeAddress("beijing");
address1.setCompanyAddress("shanghai");
people1.setId(1);
people1.setName("zhangsan");
people1.setAddress(address1);
People people11 = new People();
people11.setId(5);
people11.setName("zhangsan11");
People people12 = new People();
people12.setId(6);
people12.setName("zhangsan12");
List<People> list1 = new ArrayList<People>();
list1.add(people11);
list1.add(people12);
people1.setFriends(list1);
System.out.println("-------------------");
People people2 = new People();
Address address2 = new Address();
address2.setCompanyAddress("liaoning");
address2.setHomeAddress("jilin");
people2.setId(2);
people2.setName("lisi");
people2.setAddress(address2);
People people21 = new People();
people21.setId(3);
people21.setName("lisi21");
People people22 = new People();
people22.setId(4);
people22.setName("lisi22");
List<People> list2 = new ArrayList<People>();
list2.add(people21);
list2.add(people22);
people2.setFriends(list2);
list.add(people1);
list.add(people2);
Gson gson = new Gson();
String returnData = gson.toJson(list);
resp.setContentType("text/json;charset=utf-8");
PrintWriter pw = resp.getWriter();
pw.print(returnData);
pw.flush();
}
}
使用到的Address类代码如下:
package com.json.dto;
public class Address {
private String homeAddress;
private String companyAddress;
public String getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
public String getCompanyAddress() {
return companyAddress;
}
public void setCompanyAddress(String companyAddress) {
this.companyAddress = companyAddress;
}
}
使用到的People类代码如下:
package com.json.dto;
import java.util.List;
public class People {
private int id;
private String name;
private Address address;
private List<People> friends;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<People> getFriends() {
return friends;
}
public void setFriends(List<People> friends) {
this.friends = friends;
}
}