随笔-84  评论-56  文章-0  trackbacks-0
 

AJAX JSON 发送请求数据

Ø 使用XML 向服务器发送复杂的数据结构,

Ø 通过串连接来创建XML 串并不好,

Ø 这也不是用来生成或修改XML 数据结构的健壮技术。

Ø JSQN 概述

 * JSON XML 的一个替代方法,可以在www.Json.org 找到。

 * JSON 是一种文本格式,它独立于具体语言,

 * 使用了与C 系列语言(C C# JavaScript )类似的约定。

 * JSON建立在以下 两种数据结构基础上,当前几乎所有编程语言都支持这两种数据结构。

两种数据结构

Ø /值对集合。

 * 不同的语言中,它被理解为对象(object),纪录 record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 associative array)。


     

Ø  值的有序表。

 * 这通常实现为一个数组。

JSON的数据结构

Ø JSON对象

 *  对象是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间使用“,”(逗号)分隔。



    

Ø JSON数组

    * 数组是值(value)的有序集合。一个数组以“[”(左中括号)开始,“]”(右中括号)结束。值之间使用“,”(逗号)分隔。




Ø 

    * 值(value)可以是双引号括起来的字符串(string)、数值(number)truefalse null、对象(object)或者数组(array)。这些结构可以嵌套。



Ø 字符串(string

字符串(string)是由双引号包围的任意数量Unicode字符的集合,使用反斜线转义。一个字符(character)即一个单独的字符串(character string)。

字符串(string)与C或者Java的字符串非常相似。




Ø 数值(number

    * 数值(number)也与C或者Java的数值非常相似。除去未曾使用的八进制与十六进制格式。除去一些编码细节。



Ø 空白可以加入到任何符号之间。 以下描述了完整的语言。

Ø http://www.json.org/能得到JSON

DEMO JSON对象

Ø 我们可以以Employee对象的简单的例子展开进行。

Ø Employee对象可能包含姓、名、员工号和职位等数据。

Ø 使用JSON,可以如下表示Employee对象实例:

var employee = {

 “firstName”:”Zhou”,

 “lastName”:”DaQing”,

 “employeeNumber”:517,

 “title”:”Accountant”

}

Ø 然后可以使用标准点记法使用对象的属性,如下所示:

var lastName = employee.lastName;

var title = employee.title;

employee.employee = 517;

JSONXML

Ø JSON 是一个轻量级的数据互换格式。

Ø 如果用 XML 来描述同样的employee对象,可能如下所示:

<employee>

    <firstName>Zhou</firstName>

    <lastName>DaQing</lastName>

    <employeeNumbe>517</employeeNumbe>

    <title>Accountant</title>

</employee >

Ø 显然,JSON编码比XML 编码简短。

Ø 如果在网络上发送大量数据,可能会带来显著的性能差异。

Ø www.Json.org 网站列出了至少与其他编程语言的14种绑定

Ø 这说明,不论在服务器端使用何种技术,都能通过JSON与浏览器通信。

JSON

Ø 因为这些结构得到了如此众多编程语言的支持,所以JSON 可以作为异构系统之间的一种数据互换格式。

Ø 另外,由于JSON 是基于标准JavaScript 的子集,所以在所有当前Web 浏览器上都应该是兼容的。

DEMO AJAX JSON 发送请求数据

Ø DEMO

 * 使用JSON JavaScript 对象转换为串格式,

 * Ajax 将这个串发送到服务器,

 * 服务器根据这个串创建一个对象.

Ø 撰写“jsonExample.html”,如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

        "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

 <title>JSON Example</title>

   <script type="text/javascript" src="/js/json2.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();

             var carAsJSON = JSON.stringify(car);

             alert("Car object as JSON:"n" + 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","Coronet R/T",1989,"pink");

        }

        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" onblur="doJSON();"/>

</form>

   <h2>Server Response:</h2>

<div id="serverResponse"></div>

</body>

</html>

DEMO 服务器端接收JSON数据

Ø 然后撰写“JSONExample.java”文件,内容如下:

package org.yifeng.webapp.servlet;

import org.json.JSONObject;

import org.json.JSONException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.ServletException;

import java.io.IOException;

import java.io.BufferedReader;

import java.text.ParseException;

/**

 * Copyright:       晟软科技

 * WebSit:          http://www.shengruan.com

 * Author:          忆风

 * QQ:              583305005

 * MSN:             YiFengs@msn.com

 * Email:           zhdqCN@gmail.com

 * CreationTime:    2008-8-26 0:49:12

 * Description:

 */

public class JSONExample extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String json = readJSONStringFromRequestBody(request);

        //返回输出结果

        String responseText = null;

        //使用JSON绑字Ajax对象

        JSONObject jsonObject = null;

        try {

            jsonObject = new JSONObject(json);

            responseText = "You have a " + jsonObject.getInt("year") + " "

                    + jsonObject.getString("make") + " " + jsonObject.getString("model")

                    + " " + " that is " + jsonObject.getString("color") + " in color.";

        } catch (JSONException e) {

            e.printStackTrace(); 

        }

        response.setContentType("text/xml");

        response.getWriter().print(responseText);

    }

    private String readJSONStringFromRequestBody(HttpServletRequest request) {

        StringBuilder json = new StringBuilder();

        String line = null;

        try {

            BufferedReader reader = request.getReader();

            while ((line = reader.readLine()) != null) {

                json.append(line);

            }

        } catch (IOException e) {

            System.out.println("Error reading JSON stirng: " + e.toString());

        }

        return json.toString();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request, response);

    }

}

Ø 点击按钮,显示如下:

OK,看看,数据都显示出来了吧,呵呵!!!




作者:周大庆(zhoudaqing)
网址:http://www.blogjava.net/yifeng
>>>转载请注明出处!<<<

posted on 2008-08-26 02:57 忆风 阅读(284) 评论(0)  编辑  收藏 所属分类: Ajax

只有注册用户登录后才能发表评论。


网站导航: