使用JSON向服务器发送数据

  Ajax中可以使用xml作为参数发送给服务器,除了XML还可以使用JSON(http://www.json.org/json-zh.html
  XML的一个替代方法是JSON,JSON是一种文本格式,它独立于具体语言,JSON建立在以下两种数据结构基础上:
  名/值对集合,在不同的语言中,被实现为一个对象、记录、结构或字典
  值的有序表,在大部分语言中,实现为数组

       JSON可以做为异构系统之间的一种数据互换格式。
       JSON对象是名/值对的无序集合({},使用“:”分隔),JSON数组是一个有序的值集合([],使用“,”分隔)
 
       如下就是一个JSON格式的数据:

var employee = {
       “firstName” : John
       , “lastName” : Doe
       , “employeeNumber : 123
       , ”title” : “Accountant”
}

        可是使用标准点记法使用对象的属性:

var lastName = employee.lastName;        //Access the last Name
var title = employee.title;                  //Access the title
employee.employeeNumber = 456;        //Change the employee number

        通过JSON.js的carAsJSON=JSON.stringify(car)方法把一个对象转换成JSON格式,然后send(carAsJSON)发送,在Java Servlet端采用new JSONObject(carAsJSON)方法生成JSONObject对象,然后可以使用其getInt、getString等方法获取其中的值。

 
如下一个简单例子:
jsonExample.html:(其中需要到JSON网站下载json.js文件)

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >
< html >
  
< head >
    
< title > jsonExample.html </ title >

    
< script  type ="text/javascript"  src ="json.js" ></ script >
    
< script  type ="text/javascript" >
    
var xmlHttp;
    
    
function createXMLHttpRequest()
    
{
        
if ( window.ActiveXObject )
        
{
            xmlHttp 
= new ActiveXObject("Microsoft.XMLHTTP");
        }

        
else if ( window.XMLHttpRequest )
        
{
            xmlHttp 
= new XMLHttpRequest();
        }

    }

    
    
function doJSON()
    
{
        
var car = getCarObject();
        
        
//Use the JSON JavaScript library to stringify the Car object
        var carAsJSON = JSON.stringify(car);
        alert(
"Car object as JSON:  " + carAsJSON);
        
        
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(carAsJSON);
    }

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

        }

    }

    
    
function parseResults()
    
{
        
var responseDiv = document.getElementById("serverResponse");
        
if ( responseDiv.hasChildNodes() )
        
{
            responseDiv.removeChild(responseDiv.childNodes[
0]);
        }

        
        
var responseText = document.createTextNode(xmlHttp.responseText);
        responseDiv.appendChild(responseText);
    }

    
    
function getCarObject()
    
{
        
return new Car("Dodge""Coroner R/T"1969"yellow");
    }

    
    
function Car(make, model, year, color)
    
{
        
this.make = make;
        
this.model = model;
        
this.year = year;
        
this.color = color;
    }

    
</ script >
    
  
</ head >
  
  
< body >
    
< br />< br />
    
< form  action ="#" >
        
< input  type ="button"  value ="Click here to send JSON data to the server"
            onclick
="doJSON();"   />
    
</ form >
    
    
< h2 > Server Response: </ h2 >

    
< div  id ="serverResponse" ></ div >
  
</ body >
</ html >
JSONExample.java:(其中需要到JSON网站下载org.json.JSONObject包)
package  com.asima.chap3;

import  java.io.BufferedReader;
import  java.io.IOException;
import  java.text.ParseException;

import  javax.servlet.ServletException;
import  javax.servlet.http.HttpServlet;
import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;

import  org.json.JSONObject;

/**
 *
 * 
@author asima
 * @date   2007-2-4
 
*/

public   class  JSONExample  extends  HttpServlet
{
    
protected void doPost(HttpServletRequest request, HttpServletResponse response)
    
throws ServletException, IOException
    
{
        String json 
= readJSONStringFromRequestBody(request);
        
        
//Use the JSON-Java binding library to create a JSON object in Java
        JSONObject jsonObject = null;
        
try
        
{
            jsonObject 
= new JSONObject(json);
        }

        
catch ( ParseException pe)
        
{
            System.out.println(
"ParseException: " + pe.toString());
        }

        
        String responseText 
= "You have a " + jsonObject.getInt("year"+ " " +
            jsonObject.getString(
"make"+ " " + jsonObject.getString("model"+ " " +
            
" that is " + jsonObject.getString("color"+ " in color.";
        
        response.setContentType(
"text/xml");
        response.getWriter().print(responseText);
    }

    
    
private String readJSONStringFromRequestBody(HttpServletRequest request)
    
{
        StringBuffer json 
= new StringBuffer();
        String line 
= null;
        
try
        
{
            BufferedReader reader 
= request.getReader();
            
while((line = reader.readLine()) != null )
            
{
                json.append(line);
            }

        }

        
catch ( Exception e)
        
{
            System.out.println(
"Error in readJSONStringFromRequestBody: " + e.toString());
        }

        
return json.toString();
    }

}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值