[ajax 學習筆記] json資料格式

來源:互聯網
上載者:User

標籤: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 變數中。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.