標籤:http java 使用 os io 資料 for cti
之前寫過ajax傳送資料可以用普通文本和XML兩種格式。這裡記一下json資料格式。
json:javascript object notation。
之前分析過,用文本和XML傳送資料各有優劣。而json可以輕鬆地將javascript對象轉換成可以隨時發送的資料。
一個json資料例子:
var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "[email protected]" }, { "firstName": "Jason", "lastName":"Hunter", "email": "[email protected]" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "[email protected]" } ], "authors": [ { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }, { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }, { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ] }訪問json資料:
people.programmers[0].lastName;
修改json資料:
people.musicians[1].lastName = "Rachmaninov";
轉換回字串:
String newJSONtext = people.toJSONString();
json最大的價值在於將javascript真的作為javascript而非資料格式語言進行處理。
將json發送個伺服器:
1)get方式
var url = "organizePeople.php?people=" + escape(people.toJSONString());request.open("GET", url, true);request.onreadystatechange = updatePage;request.send(null);這樣做有兩個缺點:
1> 在使用 GET 請求發送大塊資料時,對 URL 字串有長度限制。雖然這個限制很寬泛,但對象的 JSON 字串表示的長度可能超出您的想象,尤其是在使用極其複雜的對象時更是如此。
2> 在跨網路以純文字發送所有資料的時候,發送資料面臨的不安全性超出了您的處理能力。
2)post方式
var url = "organizePeople.php?timeStamp=" + new Date().getTime();request.open("POST", url, true);request.onreadystatechange = updatePage;request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");request.send(people.toJSONString());
伺服器解析json
處理 JSON 的兩步驟
1> 針對編寫伺服器端程式所用的語言,找到相應的 JSON 解析器/工具箱/協助器 API。
2> 使用 JSON 解析器/工具箱/協助器 API 取得來自客戶機的請求資料並將資料轉變成指令碼能理解的東西。
使用json解析器
php解析json用的是json-php模板
// This is just a code fragment from a larger PHP server-side scriptrequire_once('JSON.php');$json = new Services_JSON();// accept POST data and decode it$value = $json->decode($GLOBALS['HTTP_RAW_POST_DATA']);// Now work with value as raw PHP通過該模板,可將獲得的所有資料(數組格式的、多行的、單值的或 JSON 資料結構中的任何內容)轉換成原生 PHP 格式,放在 $value 變數中。