跳至內容

JavaScript/Handling JSON

維基教科書,自由的教學讀本

本地JSON

[編輯]

現代JSON處理

[編輯]

處理JSON可能需要添加一個支持庫,該庫創建全局JSON對象。此對象僅在新瀏覽器(例如 FF 3.5、IE8)中原生存在。 可以在這裡找到這樣的庫:

//Parsing JSON: var myObject = JSON.parse(myJSONtext) //Creating JSON: var myJSONText = JSON.stringify(myObject); 

老方法

[編輯]

在舊瀏覽器中,您可以使用以下語法,但這會引發安全問題,例如跨站腳本(XSS)。

var myObject = eval("(" + myJSONtext + ")") 

JSONP

[編輯]
維基百科中的相關條目:

鑑於瀏覽器對 cross-domain Ajax 的限制(僅在一些早期瀏覽器中通過配置、在IE8中通過非標準方式以及在HTML5中使用伺服器標頭允許),一種規避此類限制的方法(同時仍需要一些伺服器端腳本協調)用於站點將HTML腳本標記動態插入到其代碼中,由此它們所針對的跨域腳本(通常)提供JSON,但包裝在函數調用中(函數名稱根據請求者提供的「回調」參數)或其他一些可執行代碼。

在PHP中,可以像下面這樣簡單地提供這樣的 JSONP:

<?php if (isset($_GET['callback'])) { header('Content-Type: application/javascript'); $our_site_data = ... // Set to an array or object containing data to be supplied for use at other sites print $_GET['callback'] . '(' . json_encode($our_site_data) . ')'; } ?> 

jQuery 和其他框架有自己的生成 JSONP 請求的方法,但我們將使用以下自定義代碼。

注意:請務必記住,如果目標站點或目標站點提供的數據可能來自不可靠的來源,則不應使用以下代碼,因為此類腳本可能以使用站點的權限運行(例如,讀取用戶cookie並將其傳遞到另一個站點),從而執行跨站腳本攻擊。

<script> var JSONP = function(global) { // Introduces only one global  // MIT Style license, adapted from http://devpro.it/code/209.html  function JSONP(uri, callback) {  function JSONPResponse() {  // Reduce memory by deleting callbacks when finished  try { delete JSONP[src] } catch(e) { JSONP[src] = null; }  documentElement.removeChild(script);  // Execute the user's callback with the arguments supplied by the server's JSONP call  if (typeof callback === 'string') { // Assumes only one return argument and that it is an HTML string  document.getElementById(callback).innerHTML = arguments[0];  } else {  callback.apply(this, arguments);  }  }  // Ensure a unique callback  var src = '_' + id++,  script = document.createElement("script");  // Add our callback as a property of this JSONP  // function to avoid introducing more globals  JSONP[src] = JSONPResponse;  // We include "callback", as it is typically used in  // JSONP (e.g., on Wikibooks' API) to specify the callback  documentElement.insertBefore(  script,  documentElement.lastChild  ).src = uri + (uri.indexOf('?') === -1 ? '?' : '&') + "callback=JSONP." + src;  }  var id = 0, documentElement = document.documentElement;  return JSONP; }(this); // Get the parsed HTML of this page you are reading now // using the Mediawiki API (See http://en.wikibooks.org/w/api.php // for Wikibooks, but it also applies at other Mediawiki wikis) that // allows for such cross-domain calls JSONP('http://en.wikibooks.org/w/api.php?action=parse&format=json&page=JavaScript/Handling_JSON',  function (data) {  alert(data.parse.text['*']);  } ); </script> 

更多信息

[編輯]