日期:2014-05-16  浏览次数:20340 次

Json Ajax小例子【转】
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式, 易于人阅读和编写,
JSON建构于两种结构:
(1)“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
(2)值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。
ajax已成为一种热门的js异步执行的技术,但是在前端页面传递参数时,一般有两种方式,一种是将参数组装成字符串,通过Get或者Post方式发送除去,这种方式适合于参数不多,内容不丰富的情况。另外一种是要传递丰富的参数,一般就要使用连接字符串的方式将它组装成一定格式的xml内容,既不方便阅读,也很麻烦,这时,JSON就体现出它的优势,结合JSON-Java library,在后台服务可以很容易的解析请求的参数值。下面就实现一个从前台页面发送一些json格式的字符串给后台,后台解析后返回一些信息在前台页面展示的功能。

1 创建前台页面index.jsp里调用ajax请求,js如下
Js代码 
<script type="text/javascript" src="js/json.js"></script> 
<script type="text/javascript"> 
//创建xmlhttp对象 
var xmlHttp; 
function  createXMLHttpRequest()  { 
  if  (window.ActiveXObject)  { 
     xmlHttp  =   new  ActiveXObject("Microsoft.XMLHTTP"); 
  }   
  else   if  (window.XMLHttpRequest)  { 
     xmlHttp  =   new  XMLHttpRequest(); 
  }  
}  
//创建Person类有参构造器 
function Person(name,age,gender,birthday){ 
    this.age = age; 
    this.gender = gender; 
    this.name = name; 
    this.birthday = birthday; 

//创建一个Person的对象 
function getPerson(){ 
    return new Person("coco",25,true,"1988-08-08"); 

//发起ajax请求 
function doJSON(){ 
   var  person  =  getPerson(); 
    
   //使用json.js库里的stringify()方法将person对象转换成Json字符串  
   var  personAsJSON  =  JSON.stringify(person); 
   alert( " Car object as JSON:\n  "   +  personAsJSON); 
    
   var url = "JSONExample?timeStamp="+new Date().getTime(); 
    
   createXMLHttpRequest(); 
   xmlHttp.open("POST",url,true ); 
   xmlHttp.onreadystatechange  =  handleStateChange; 
   xmlHttp.setRequestHeader("Content-Type" ,"application/x-www-form-urlencoded");     
   xmlHttp.send(personAsJSON); 

 
function  handleStateChange()  { 
    if (xmlHttp.readyState  ==   4 )  { 
        if (xmlHttp.status  ==   200 )  { 
            parseResults(); 
        }  
    }  

 
function  parseResults()  { 
    var  responseDiv  =  window.document.getElementById("responseDiv"); 
    var content = xmlHttp.responseText 
    responseDiv.value = content; 

</script> 
在这段js中,构造了一个Person对象,然后调用Json.js库的stringify方法,将person对象组装成Json格式的字符串发送到后台处理的servlet,当收到后台处理后返回的数据时,在页面里进行展示。

2 后台处理的Servlet,内容如下:
Java代码 
public class JSONExample extends HttpServlet{ 
 
    @Override 
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)