AJAX以 JSON 發(fā)送請求數(shù)據(jù)
Ø 使用XML 向服務(wù)器發(fā)送復(fù)雜的數(shù)據(jù)結(jié)構(gòu),
Ø 通過串連接來創(chuàng)建XML 串并不好,
Ø 這也不是用來生成或修改XML 數(shù)據(jù)結(jié)構(gòu)的健壯技術(shù)。
Ø JSQN 概述
* JSON 是 XML 的一個(gè)替代方法,可以在www.Json.org 找到。 * JSON 是一種文本格式,它獨(dú)立于具體語言, * 使用了與C 系列語言(如C 、C# 、JavaScript 等)類似的約定。 * JSON建立在以下 兩種數(shù)據(jù)結(jié)構(gòu)基礎(chǔ)上,當(dāng)前幾乎所有編程語言都支持這兩種數(shù)據(jù)結(jié)構(gòu)。 |
兩種數(shù)據(jù)結(jié)構(gòu)
Ø 名/值對集合。
* 不同的語言中,它被理解為對象(object),紀(jì)錄 (record),結(jié)構(gòu)(struct),字典(dictionary),哈希表(hash table),有鍵列表(keyed list),或者關(guān)聯(lián)數(shù)組 (associative array)。 |
Ø 值的有序表。
* 這通常實(shí)現(xiàn)為一個(gè)數(shù)組。 |
JSON的數(shù)據(jù)結(jié)構(gòu)
Ø JSON對象
* 對象是一個(gè)無序的“‘名稱/值’對”集合。一個(gè)對象以“{”(左括號)開始,“}”(右括號)結(jié)束。每個(gè)“名稱”后跟一個(gè)“:”(冒號);“‘名稱/值’ 對”之間使用“,”(逗號)分隔。 |

Ø JSON數(shù)組
* 數(shù)組是值(value)的有序集合。一個(gè)數(shù)組以“[”(左中括號)開始,“]”(右中括號)結(jié)束。值之間使用“,”(逗號)分隔。 |

Ø 值
* 值(value)可以是雙引號括起來的字符串(string)、數(shù)值(number)、true、false、 null、對象(object)或者數(shù)組(array)。這些結(jié)構(gòu)可以嵌套。 |

Ø 字符串(string)
* 字符串(string)是由雙引號包圍的任意數(shù)量Unicode字符的集合,使用反斜線轉(zhuǎn)義。一個(gè)字符(character)即一個(gè)單獨(dú)的字符串(character string)。 * 字符串(string)與C或者Java的字符串非常相似。 |

Ø 數(shù)值(number)
* 數(shù)值(number)也與C或者Java的數(shù)值非常相似。除去未曾使用的八進(jìn)制與十六進(jìn)制格式。除去一些編碼細(xì)節(jié)。 |

Ø 空白可以加入到任何符號之間。 以下描述了完整的語言。
Ø 在http://www.json.org/能得到JSON。
DEMO JSON對象
Ø 我們可以以Employee對象的簡單的例子展開進(jìn)行。
Ø Employee對象可能包含姓、名、員工號和職位等數(shù)據(jù)。
Ø 使用JSON,可以如下表示Employee對象實(shí)例:
var employee = { “firstName”:”Zhou”, “lastName”:”DaQing”, “employeeNumber”:517, “title”:”Accountant” } |
Ø 然后可以使用標(biāo)準(zhǔn)點(diǎn)記法使用對象的屬性,如下所示:
n var lastName = employee.lastName;
n var title = employee.title;
n employee.employee = 517;
JSON與XML
Ø JSON 是一個(gè)輕量級的數(shù)據(jù)互換格式。
Ø 如果用 XML 來描述同樣的employee對象,可能如下所示:
<employee> <firstName>Zhou</firstName> <lastName>DaQing</lastName> <employeeNumbe>517</employeeNumbe> <title>Accountant</title> </employee > |
Ø 顯然,JSON編碼比XML 編碼簡短。
Ø 如果在網(wǎng)絡(luò)上發(fā)送大量數(shù)據(jù),可能會(huì)帶來顯著的性能差異。
Ø www.Json.org 網(wǎng)站列出了至少與其他編程語言的14種綁定 。
Ø 這說明,不論在服務(wù)器端使用何種技術(shù),都能通過JSON與瀏覽器通信。
JSON
Ø 因?yàn)檫@些結(jié)構(gòu)得到了如此眾多編程語言的支持,所以JSON 可以作為異構(gòu)系統(tǒng)之間的一種數(shù)據(jù)互換格式。
Ø 另外,由于JSON 是基于標(biāo)準(zhǔn)JavaScript 的子集,所以在所有當(dāng)前Web 瀏覽器上都應(yīng)該是兼容的。
DEMO AJAX以 JSON 發(fā)送請求數(shù)據(jù)
Ø DEMO
* 使用JSON 將JavaScript 對象轉(zhuǎn)換為串格式, * Ajax 將這個(gè)串發(fā)送到服務(wù)器, * 服務(wù)器根據(jù)這個(gè)串創(chuàng)建一個(gè)對象. |
Ø 撰寫“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 服務(wù)器端接收JSON數(shù)據(jù)
Ø 然后撰寫“JSONExample.java”文件,內(nèi)容如下:
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: 憶風(fēng) * 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); //返回輸出結(jié)果 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); } } |
Ø 點(diǎn)擊按鈕,顯示如下:
OK,看看,數(shù)據(jù)都顯示出來了吧,呵呵!!!
作者:周大慶(zhoudaqing)
網(wǎng)址:http://www.aygfsteel.com/yifeng
>>>轉(zhuǎn)載請注明出處!<<<