跳转到内容

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> 

更多信息

[编辑]