andrewYe 发表于 2013-1-23 02:20:54

json格式的 jquery ajax 实例

jquery使ajax的开发大大的简化,做ajax的应用,前台和后台的数据传输时必然的。通常,我们可以使用普通的字符串作为前后台传输的数据(例如使用特殊字符将各个元素分隔开,在后台用split处理等等)。当传输的数据量比较大,或者数据的格式比较复杂时,我们可以考虑使用json或者xml的格式来对数据封装,传输。
jquery的ajax函数做的非常的棒,我们可以调用已经封装好的$.get(),$.post(),$.ajax(),前两个函数是最后一个函数的特殊,也就是说$.ajax()可以让我们的ajax之旅的操控性更强。
下面是一个利用json传输的简单例子:
 
import org.json.*;public class MyBean {private String name;private int num;private int array[];public String getName() {return name;}public void setName(String name) {this.name = name;}public int getNum() {return num;}public void setNum(int num) {this.num = num;}public int[] getArray() {return array;}public void setArray(int[] array) {this.array = array;}public JSONObject toJson() {JSONObject obj;try { obj= new JSONObject();obj.put("name", this.name);obj.put("num", this.num);JSONArray array = new JSONArray(this.array);obj.put("array", array);} catch (Exception e) {e.printStackTrace();return null;}return obj;}} 
 
只是一个简易的pojo类,用来模拟,其中有自己的toJson()方法。需要用到org.json的包
 
 
import java.io.IOException;import java.io.*;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class JsonServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubthis.doGet(request, response);}@Overrideprotected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubMyBean b = new MyBean();b.setNum(22);b.setName("andrew");int [] array={1,2,3,4};b.setArray(array);String str=(String)request.getParameter("text");System.out.println(str);PrintWriter out=response.getWriter();String data=b.toJson().toString();out.print(data);System.out.println(data);out.flush();}}  
接受ajax请求的servlet
 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type"content="text/html; charset=ISO-8859-1" /><title>Insert title here</title><scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script><script type="text/javascript">$(document).ready(function(){$("#b").click(function(){var t=$("#text1").val()$.post("json",{text:t},function(data){var name=data.name;var num=data.num;var array=data.array;$("#content1").html(name);},"json");})})</script></head><body><div id="content1"></div><input type="text" id="text1" value="default" /><input type="button" value="click me~" id="b" /></body></html> 
 
利用$.post()方法,传输json格式的数据,方法的最后一个参数设置接受数据默认为json
页: [1]
查看完整版本: json格式的 jquery ajax 实例