jquery+ajax+json实例

最近在学习使用jquery,因为需要使用ajax进行异步调用,所以在网上学习了一下。现在通过实例,把自己知道的记录下来。 

 

本人通过jsp,servlet分别担任前端与后台处理,jsp通过jquery的ajax调用Servlet,后台处理之后得到的信息返回前端。 

 

servlet后台对象转化为json格式,可以通过两种方式:

1.fastjson-1.1.1.jar(此方法使用比较简便)

2.json-lib-2.4-jdk15.jar(此方法在代码中也有使用,已经注释) 

 

首先在web.xml部署一个简单的servlet(DemoServlet): 

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  	<servlet-name>demoServlet</servlet-name>
  	<servlet-class>servlet.DemoServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>demoServlet</servlet-name>
  	<url-pattern>/demoServlet</url-pattern>
  </servlet-mapping>
</web-app>

 

 

estAjaxPojo包中定义两个pojo:

Address.java

package testAjaxPojo;

public class Address implements java.io.Serializable{
	private String province;       
	private String city;        
	private String country;
	
	public Address() {
		
	}         
	
	public Address(String province, String city, String country) {
		this.province = province;            
		this.city = city;             
		this.country = country;        
	}
	
	public String getProvince() {
		return province;
	}
	public void setProvince(String province) {
		this.province = province;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
	
	
}

 

  Person.java

 

package testAjaxPojo;

package testAjaxPojo;

public class Person implements java.io.Serializable{
	private String name;        
	private String sex;        
	private Integer age;        
	private Address address;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	} 
	
	
}

 
 servlet.DemoServlet.java

package servlet;

import java.io.IOException;
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.alibaba.fastjson.JSON;

import testAjaxPojo.Address;
import testAjaxPojo.Person;

public class DemoServlet 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 {
		resp.setContentType("text/xml;charset=utf-8");
		resp.setHeader("Cache-Control","no-cache"); 
		String str = req.getParameter("actionId");
		System.out.println(str);
		try{                                 
			Person person1 = new Person();
			person1.setName("小王");
			person1.setSex("女");
			person1.setAge(23);
			person1.setAddress(new Address("辽宁省","大连市","高新园区"));
			
			List<Person> list = new ArrayList<Person>();
			list.add(person1);
			
			
			resp.getWriter().write(JSON.toJSONString(list));
			/*try {
				JSONArray jsonArray = JSONArray.fromObject(list);
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("person", jsonArray);
				resp.getWriter().write(jsonObject.toString());
				
			}catch (IOException e) {
				e.printStackTrace();
			}*/
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}

 
  servlet已经完成,现在就需要jsp通过jquery的ajax方法调用返回的数据进行分析,就可以得到想要的结果index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
<script type="text/javascript">
function addPerson(){
	$.ajax({ 
	    type: "post", 
	    url: "demoServlet?actionId=100", 
	    dataType: "json", 
	    success: function (data) { 
	    	var json = eval(data);
	    	$.each(json, function(i, p) {
				$("#name").text(p.name);
				$("#age").text(p.age);
				$("#sex").text(p.sex);
				$("#address").text(p.address.province + p.address.city + p.address.country);
			});
	    	/* var list = data.person;
			$.each(list, function(i, p) {
				$("#name").text(p.name);
				$("#age").text(p.age);
				$("#sex").text(p.sex);
				$("#address").text(p.address.province + p.address.city + p.address.country);
			}); */
	    }, 
	    error: function (XMLHttpRequest, textStatus, errorThrown) { 
	            alert(errorThrown); 
	    } 
	});
}
	/* $.getJSON("demoServlet",null,function call(data) {
		var list = data.person;
		$.each(list, function(i, p) { 
			var row = $("#tr").clone();
			row.find("#name").text(p.name);
			row.find("#age").text(p.age);
			row.find("#sex").text(p.sex);
			row.find("#address").text(p.address.province + p.address.city + p.address.country);
			row.appendTo("#tbody");
			});
		});
	} */
	</script>
  </head>
  
  <body>
    <input type="button" value="JsonView" onClick="addPerson();">
    <div id="dateMessage">
    <table id="planTable" border="1">
	    <tr>              
		    <td>Name</td>             
		    <td>Sex</td>             
		    <td>Age</td>              
		    <td>Address</td>         
	    </tr>                
	    <tbody id="tbody">
	    <tr id="tr">
		    <td id="name"></td>                 
		    <td id="sex"></td>                 
		    <td id="age"></td>                  
		    <td id="address"></td> 
        </tr>               
        </tbody>     
	</table>       
</div> 
</body>
</html>

 

到此实现简单的功能

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值