生成json格式的字符串。
需要相关包
json-lib-2.3-jdk15.jar
morph-1.1.1.jar
morph-sandbox-1.1.1.jar
ezmorph-1.0.6.jar
commons-logging-1.1.1.jar
commons-lang-2.5.jar
commons-collections-3.2.1.jar
commons-beanutils-1.8.3.jar
1 package cn.itcast.controller; 2 3 import static org.junit.Assert.*; 4 5 import java.util.ArrayList; 6 import java.util.List; 7 8 import net.sf.json.JSONArray; 9 import net.sf.json.JSONObject; 10 import net.sf.json.JsonConfig; 11 12 import org.junit.Test; 13 14 import cn.itcast.domain.Province; 15 16 public class JSONlibTest { 17 18 @Test 19 public void test1() { 20 Province p = new Province("山东省","250000"); 21 JSONObject jsonObj = JSONObject.fromObject(p); 22 System.out.println(jsonObj.toString()); 23 } 24 @Test 25 public void test2() { 26 List<Province> ps = new ArrayList<Province>(); 27 ps.add(new Province("安徽省", "001")); 28 ps.add(new Province("浙江省", "002")); 29 ps.add(new Province("江苏省", "003")); 30 JSONArray jsonArr = JSONArray.fromObject(ps); 31 System.out.println(jsonArr.toString()); 32 } 33 @Test 34 public void test3() { 35 List<Province> ps = new ArrayList<Province>(); 36 ps.add(new Province("安徽省", "001")); 37 ps.add(new Province("浙江省", "002")); 38 ps.add(new Province("江苏省", "003")); 39 40 JsonConfig cfg = new JsonConfig();//JSON串过滤 41 cfg.setExcludes(new String[]{"zipcode"});//不包含的字段列表 42 43 JSONArray jsonArr = JSONArray.fromObject(ps,cfg); 44 System.out.println(jsonArr.toString()); 45 } 46 }
jsp页面中
1 2 var data=this.responseText; 3 4 var provinceJson=eval("("+data+")");
ajax参考
1 <%@ page language="java" pageEncoding="UTF-8"%> 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 3 <html> 4 <body> 5 <input type="button" value="AJAX休验"/> 6 <script type="text/javascript"> 7 document.getElementsByTagName("input")[0].onclick=function(){ 8 //创建AJAX引警 9 var xhr = createAJAX(); 10 //准备发送异步请求 11 var method = "GET"; 12 var url = "${pageContext.request.contextPath}/TimeServlet?method=newType&time="+new Date().getTime(); 13 xhr.open(method,url); 14 //真正发送异步请求体数据 15 xhr.send(null); 16 //接收服务端响应的数据 17 xhr.onreadystatechange = function(){ 18 if(xhr.readyState==4){ 19 if(xhr.status==200){ 20 var now = xhr.responseText; 21 //将now变量的值,动态添加到<div>元素节点之间 22 var divElement = document.getElementsByTagName("div")[0]; 23 divElement.innerHTML = "<B>"+now+"</B>"; 24 } 25 } 26 }; 27 } 28 //创建AJAX引警,即XMLHttpRequest对象,它是一个异步对象, 29 function createAJAX(){ 30 var xhr = null; 31 try{ 32 //如果是IE浏览器的话,不管什么版本 33 xhr = new ActiveXObject("microsoft.xmlhttp"); 34 }catch(e1){ 35 try{ 36 //如果是非IE浏览器的话 37 xhr = new XMLHttpRequest(); 38 }catch(e2){ 39 window.alert("你的浏览器非主流,请更换为主流浏览器"); 40 } 41 } 42 return xhr; 43 } 44 45 </script> 46 <hr/> 47 <div> 48 </div> 49 <hr/> 50 51 </body> 52 </html>