ajax的json框架

其实json的核心思想就是对象和字符串在服务器端和客户端的相互转化,通过json.jar和json.js来实现,可以使服务器端接收上来的数据自动进行实体的转换,也使得客户端不用再因拼接字符串而烦恼.
是比 xml 更好的数据格式 :
       1) 能够表示出 复杂的数据结构  .
       2) 在客户端 和 服务器 端都能够很方便的解析 .
-----------------------------------------------------------------------
 JSON :
     1, 定义了一种描述数据的格式 .
         student( id , name , age , email ) ;
        
         "{ 'id':'1' , 'name':'zhangsan' , 'age':10 ,
            'email':'zhangsan@cernet.com' ,
            'address' : { 'street':'xxxx' , 'postcode':'1111'
                          } ,  
            'phone' : ['1111' , '22222' , '33333']
          }"


     2, json.js 提供了两个函数 .
         javascript object <---> str
        |-> stringify( object ) --> str
        |-> parse( str ) --> obj
     3, json.jar  在服务器端的java代码中 对json 字符串进行转化 .
      
    XmlHttpRequest
     |-> user{ id , name , age , email .}  [javascript]
     |-> json.js --> string( json format) .
    
   
    string (json format)===> Server ( java object )
      ==> json.jar ( string --> java object )
    
     {   "id":1,
        "name":"zhangsan",
        "age":20,
        "email":[ "emailA","emailB","emailC"] ,
        "address": { "street":"aaaaa","postcode":"1234"}
     }
    
    JSON.stringify( obj ) ===> str :
向服务器发送数据之前调用 ,将要发送的数据保存在对象中 obj---stringify --> str ===> server  
   
    JSON.parse( str ) --> Obj:
       接受到服务器的应答(str)之后, 调用parse将服务器应答的字符串转化为对象,对其中的数据进行使用 。   
    Client:
    button --> onclick --> reg()
     |-> createUser
     |-> JSON.stringify() -> string
     |-> send( string )  ....
   
    Serlvet:
       readJsonString() : get string from request .
       new JSONObject( str );
       insert() :   get data from JSONObject
       respnose :
         |-> ok
         |-> error ;
        
        
    reqCallBack()
       |-> alert( ok ) ;
       |-> alert( error ) ;
服务器从客户端接收数据的方式:
                 request.getInputStream()
                 ==> InputStream [ ==> BufferedReader ]
                 ==> is.read() | br.readLine()  => xmlData

--------------------------------------------------------------------------------------------------------------
以下为示例代码:
==============================================================================================================
//这是在页面上的对象字符串间的转化
<html>
 <head>
  <script type="text/javascript" src="./json.js"></script>
  <script type="text/javascript">
   function testStringify(){
    var obj = new Object();
    obj.id=1 ;
    obj.name="zhangsan" ;
    obj.age=20 ;
    obj.email = [ "emailA" , "emailB" , "emailC" ] ;
    obj.address= { street : "aaaaa" , postcode : "1234" } ; 
    
    var str = JSON.stringify( obj ) ;
      document.write( "<h3>" + str + "</h3>" ) ;
   }   
   
   function testParse(){
    var str = '{ "orderItem": [ { "number":10 ,"product" : { "id":1, "name":"book" , "price":10} } , { "number":2  ,"product" : {"id":2 , "name":"USB" , "price": 100} } , { "number":3  , "product" :{ "id":3 , "name":"DVD" , "price" : 5 } } ]} ' ; 
    var order = JSON.parse( str ) ;
    for( var i = 0 ; i < order.orderItem.length ; i++ ){
     document.write( "<h3>number = " + order.orderItem[i].number + "</h3>" ) ;
     document.write( "<h3> Product " + order.orderItem[i].product.id + " " +order.orderItem[i].product.name + " " + order.orderItem[i].product.price + "</h3>" ) ;
     document.write( "<hr/>" ) ;
    }
   }
  </script>
 </head>
 <body> 
  <input type="button" value="test stringify" onclick="testStringify();"/>
  <input type="button" value="test parse" onclick="testParse()"/>
 </body>
</html>
    
==============================================================================================================
//这是在Java中测试字符串向对象转化及对象转成字符串
package test.ajax.json ;
import org.json.* ;

public class TestJsonObject{
 public static void main( String args[] ) throws Exception{
  //已接收上来的串
  String str =  "{\"id\":1,\"name\":\"testjson\",\"age\":20,\"email\":[\"emailA\",\"emailB\",\"emailC\"],\"address\":   {\"street\":\"aaaaa\",\"postcode\":\"1234\"}}" ;
  //上面的/"是转意字符,其实就如此串一样,其根本原因就是区分:" {'id':1,'name':'testjson','age':20,'email':['emailA','emailB','emailC'],'address':{'street':'aaaaa','postcode':'1234'}}"
  //进行字符串向对象的转化
  JSONObject json = new JSONObject( str ) ;
  //转换后的输出
  System.out.println( "id = " + json.getInt( "id" ) ) ;
  System.out.println( "name= " + json.getString( "name" ) ) ;
  System.out.println( "age = " + json.getInt( "age" ) ) ;  
   //数组的接收
  JSONArray array = json.getJSONArray( "email" ) ;
  for( int i = 0 ; i < array.length() ; i++ ){
   System.out.println(  array.getString( i )  ) ; 
  }
    //对象中的对象处理方式
  JSONObject address = json.getJSONObject( "address" ) ;
  System.out.println( "street " + address.getString( "street" ) ) ;
  System.out.println( "postcode " + address.getString( "postcode" ) ) ;
  //对象转成字符串
  System.out.println( json.toString() ) ;
 } 
}
================================================================================================================
下面是前后台的一个应用示例:
RegServlet.java
*****************************************************************************************************************
package com.kettas.ajax ;

import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.http.*;

public class RegServlet extends HttpServlet{
 @Override
 public void service( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException {
  response.setContentType( "text/html" );
  PrintWriter out = response.getWriter();
  try{   
   String jsonStr = readJsonString( request ) ; 
   System.out.println( jsonStr ) ;
   //返回成功应答
   out.print( "ok" ) ;
   out.flush();
  }catch( Exception e ){
   e.printStackTrace();
   //返回失败应答 
   out.print( "error" ) ;
   out.flush() ;
  }
  
 }

 private String  readJsonString( HttpServletRequest request) throws Exception{
  InputStream is = request.getInputStream();
  BufferedReader br = new BufferedReader(new InputStreamReader( is ) ) ;
  String str = "" ;
  String temp = "" ;
  while( true ){
   temp = br.readLine();
   if( temp == null ){
    break ;  
   }        
   str += temp ;
  }   
  return str ; 
 } 
}
==========================================================================================================
register.html
*****************************************************************************************************************
<html> 
 <head>   
  <script type="text/javascript" src="./json.js"></script>
  <script type="text/javascript">  
   var xhr ;
   //初始化 xhr 对象
   // return value : 1 : IE , 2 , Mozila , 0 : create xhr error ;
   function createXHR(){
    //1,创建xhr 对象 .
    if( window.ActiveXObject ){
     xhr = new ActiveXObject( "Microsoft.XMLHTTP" ) ;
     return 1 ;
    }else if( window.XMLHttpRequest ){
     xhr = new XMLHttpRequest();
     return 2 ; 
    }else{
     return 0 ;
    }                           
   } 
   ////////////////// 执行用户注册 //////////////////////
   function reg(){
    //1,创建并初始化User对象
    var user = createUser();
    //2, 将User对象转化为要发送的字符串( json 格式 )
    var str = JSON.stringify( user ) ; 
    //3, 创建xhr对象                   
    createXHR();
    //4, 发送请求
    xhr.onreadystatechange = regCallBack ;
    sendRegRequest( str );
   }
   function createUser(){
    var user = new Object();
    user.name = document.getElementById( "nameId" ).value ;
    user.password = document.getElementById( "passwordId" ).value ;
    user.email = document.getElementById( "emailId" ).value ;
    user.phone = document.getElementById( "phoneId" ).value ;
    return user ; 
   }
   function sendRegRequest( data ){
    xhr.open( "post" , "/ajax/reg" ) ;
    xhr.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded" ) ;
    xhr.send( data ) ;
   }  
   function regCallBack(){
    if( xhr.readyState == 4 ){
     if( xhr.status == 200 ){
      handleRegResult(); 
     }else{
      alert( "error , status=" + xhr.status ) ;
     } 
    } 
   }
   function handleRegResult(){ 
    //alert( xhr.responseText ) ;
    if( xhr.responseText == "ok" ){
     alert( "reg ok" ) ; 
    }else if( xhr.responseText == "error" ){
     alert( "system is busy,please try again later." ) ; 
    }else{
     alert( "error!" ) ;
    } 
   }
  </script>
 </head>
 <body>
  <h1>User Register</h1>
  <table>
   <tbody>
    <tr>
     <td >User Name</td>
     <td><input type="text" id="nameId"/>
      <span id="msgId"></span>
     </td>
    </tr>
    <tr>
     <td>Password</td>
     <td><input type="password" id="passwordId" /></td>
    </tr>                                     
    <tr>
     <td>email</td>
     <td>
       <input type="text" id="emailId"/>
     </td>
    </tr>  
    <tr>
     <td>phone:</td>
     <td><input type="text" id="phoneId"/></td>
    </tr>     
    <tr>
     <td colspan="2">
      <input type="button" value="user register" onclick="reg()"/> 
     </td>
    </tr>
   </tbody>
  </table>
 </body>
</html>
==========================================================================================================
web.xml
*****************************************************************************************************************
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 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"
  version="2.5">
       <servlet>
        <servlet-name>regServlet</servlet-name>
        <servlet-class>com.kettas.ajax.RegServlet</servlet-class>
       </servlet>                                      
      
       <servlet-mapping>
        <servlet-name>regServlet</servlet-name>
        <url-pattern>/reg</url-pattern>
       </servlet-mapping>
</web-app>

posted on 2009-12-23 21:04  水无恨  阅读(865)  评论(0编辑  收藏  举报

导航