JSONP的起源

JSONP的起源

2008年09月13日 Web开发

作者:Bob Ippolito /原文链接

浏览器安全模型规定,XMLHttpRequest、框架(frame)等只能在一个域中通信。从安全角度考虑,这个规定很合理;但是,也确实给分布式(面向服务、混搭等等本周提到的概念)Web开发带来了麻烦。

为了实现跨域通信,通常的解决方案有3种:

本地代理:
需要一些硬件设施(没有服务器的客户端无法运行),并且带宽和潜伏时间也要加倍(远程服务器-代理服务器-客户端)。

Flash:
远程主机中需要部署一个crossdomain.xml文件,而且,Flash作为一门专有技术,其前途尚不明朗;换句话说,开发人员很可能要学习一种目标不确定的编程语言。

Script标签:
无法确切知道内容是否有效,没有标准的实现方法,又可能被认为是一种“安全风险”。


在此,我建议使用一种新技术,也是一种独立于标准的方法,即通过script标签来跨域获取数据,名为JSON with Padding,或者就叫JSONP。JSONP的原理很简单,但需要服务器端给予相应配合。大致来说,JSONP的实现思路就是在客户端编程时作好使用JSON数据的准备,然后再通过圆括号将这些数据括起来以创建一条有效的JavaScript语句(可能是一次有效的函数调用)。

也就是说,客户端可以使用一个用于命名jsonp的查询参数来决定可以获取的数据。最简单的情况下,如果jsonp参数为空,则返回的数据就是被括在圆括号中的JSON。

下面,我们就以del.icio.us的JSON API为例,来说明JSONP的原理。该API有一个“script tag”变量(即,可以将下面的URL作为script标签的src属性值,用以加载del.icio.us这个API提供的数据。——译者注)如下所示:

http://del.icio.us/feeds/json/bob/mochikit+interpreter:

1 if(typeof(Delicious) == 'undefined') Delicious = {};
2 Delicious.posts = [{
4 "d": "Interpreter - JavaScript Interactive Interpreter",
5 "t": [
6 "mochikit","webdev","tool","tools",
7 "javascript","interactive","interpreter","repl"
8 ]
9 }]

如果用JSONP的方式来表示,那么与此具有相同语义的URL应该是这样的:

http://del.icio.us/feeds/json/bob/mochikit+interpreter?jsonp=if(typeof(Delicious)%3D%3D%27undefined%27)Delicious%3D%7B%7D%3BDelicious.posts%3D

单纯看这个URL似乎没有什么,但我们可以要求服务器在数据有效时给出通知。因此,我可以编写一个用于跟踪数据的小系统:

01 var delicious_callbacks = {};
02 function getDelicious(callback, url) {
03 var uid = (new Date()).getTime();
04 delicious_callbacks[uid] = function () {
05 delete delicious_callbacks[uid];
06 callback();
07 };
08 url += "?jsonp=" + encodeURIComponent("delicious_callbacks[" + uid + "]");
09 // add the script tag to the document, cross fingers
10 };
11
12 getDelicious(doSomething, "http://del.icio.us/feeds/json/bob/mochikit+interpreter");

根据以上假设,用于获取数据的URL应该如下所示:

http://del.icio.us/feeds/json/bob/mochikit+interpreter?jsonp=delicious_callbacks%5B12345%5D

1 delicious_callbacks[12345]([{
3 "d": "Interpreter - JavaScript Interactive Interpreter",
4 "t": [
5 "mochikit","webdev","tool","tools",
6 "javascript","interactive","interpreter","repl"
7 ]
8 }])

可见,由于使用圆括号括住了返回的数据,这就相当于把一个JSONP请求转化成了一次函数调用,或者得到了一个纯粹的JSON直接量。服务器所要配合做的,就是在JSON数据的开头添加一小段文本(即回调函数的名称。——译者注)并将JSON数据放在括号中!

当然,接下来最好是使用Mochikit、Dojo等框架来抽象JSONP,从而让自己省去动手编写DOM以插入script标签的麻烦。

没错,JSONP只是解决了标准化的问题。假如远程主机想通过script标签向页面中注入恶意代码,而不是返回JSON数据,那么页面安全可能会随时受到威胁。不过,一旦实现了JSONP,那么对开发人员来说肯定是一件省时省力的大好事,在此基础上各种一般化的抽象、教程及文档也会应运而生的。

注:缩写词 JSONP 由 Bob Ippolito 在一篇名为 “Remote JSON – JSONP” 的文章中提出。但许多支持以 JSONP 技术实现跨域通信的厂商没有称其为 JSONP。例如,雅虎公司就称这种技术为 “JSON with callbacks”。另外,原文发表于2005年12月5日。



朋友们的留言

  1. Coach Outlet | 04月 26th, 2012 at 09:34

    By the fashion, novel appearance, sophisticated technology, superior quality, coach outlet won domestic and international customers, their products exported to the Middle East, Southeast Asia and other regions. Coach Outlet Online offers free and fast shipping. Usually, ships between 5-8 business days. So you do not need to wait for a long time.

    Reply to this comment
  2. Coach Outlet Online | 04月 26th, 2012 at 10:04

    Coach outlet online develops very quickly because it runs by its own special way and it contents the customers greatly. Five years later in 1985, the Cahns decided to sell Coach outlet after determining that none of their three children had any desire to take over the family leatherware business . Coach was then sold to Sara Lee Corporation for $30 million dollars.

    Reply to this comment
  3. Coach Outlet | 04月 26th, 2012 at 11:20

    coach outlet has always been simple,durable style features to win consumers.The products are more flexible,with easy bleaching,wear characteristics,and simply use a damp cloth. In August 2011, ICF has been sanctioned a project for manufacturing stainless steel coaches for the first time in the country. The 2,500 million project is for manufacturing technologically upgraded coach outlet canada of stainless steel shells and high speed bogies and an increase in capacity from 1,500 to 1,700 coaches.

    Reply to this comment
  4. Louis Vuitton UK | 04月 26th, 2012 at 13:37

    So excited..I have one of the black and white graffiti Louis Vuitton UK bags and they had my marine leopard stole displayed, was very proud! In 1983, the company joined with America’s Cup to form the Louis Vuitton Cup, a preliminary competition (known as an eliminatory regatta) for the yacht race.

    Reply to this comment
  5. louis vuitton | 04月 26th, 2012 at 14:08

    Further products became introduced such as the Taiga leather line in 1993, and the literature collection of Voyager Avec… in 1994. In 1996,Louis Vuitton the celebration of the Centennial of the Monogram Canvas was held in seven cities worldwide. This client oriented and faith rooted store aims at providing the best LV goods and services, such as top class louis vuitton uk and free shipping.

    Reply to this comment
  6. christian louboutin shoes | 05月 22nd, 2012 at 11:18

    I am certainly thankful to you for providing us with this invaluable info. My spouse and I are truthfully grateful, precisely the computer data we needed.Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck!

    Reply to this comment
posted @ 2012-06-01 18:02  holyes  阅读(253)  评论(0编辑  收藏  举报