加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用JSONP进行跨域的数据传递

发布时间:2020-12-16 19:26:52 所属栏目:百科 来源:网络整理
导读:使用JSONP进行跨域的数据传递 先说说浏览器的“同源策略(SOP:Same Origin Policy)”,简单的说,就是浏览器限制脚本程序只能和同协议、同域名、同端口的脚本进行交互(共享、传递变量等),cookie的传递也是遵循这个策略的。这就给一些涉及到多个服务器的应用整
使用JSONP进行跨域的数据传递

先说说浏览器的“同源策略(SOP:Same Origin Policy)”,简单的说,就是浏览器限制脚本程序只能和同协议、同域名、同端口的脚本进行交互(共享、传递变量等),cookie的传递也是遵循这个策略的。这就给一些涉及到多个服务器的应用整合带来一些麻烦,举个列子来说:

以前遇到过一个需求,在A服务器上有一个公共的服务是通过脚本程序的形式提供的,其他应用可以调用这个脚本,弹出一个窗口选择人员,然后将选择的人员ID通过一个脚本变量返回。在同一个服务器上,这个脚本工作得很好,但在B服务器上的应用调用这个脚本时,却发现获取不到返回值,其实就是由于浏览器同源策略的限制。后来采用了windows剪贴板来传递数据,但不太稳定,也有跨浏览器、跨平台的问题,这个方法很不优雅。

后来发现有一种更好的方法解决跨域数据传递的问题,其实是利用了浏览器的一个特性:虽然浏览器不允许页面中的脚本程序跨域读取内存变量,但却允许HTML引用跨域的资源,比如图片、CSS,当然也包括脚本程序。引用的脚本程序比较特殊,他被浏览器解析以后,就和本地的脚本程序没有两样,立即进行解释并执行,比如在A站点的一个js文件,内容很简单,就是一个alert(“hello world!”);,在B站点引用了这个js以后,这个脚本就会在B站点的应用中执行,显示一个警告框。由于站外脚本的引用是通过script标签来实现的,而脚本程序通过DOM的方式可以对html页面的所有标签进行控制,包括动态的创建script标签,这就可以实现调用站外程序了。把前面的alert改成一个赋值语句,不就实现了参数的传递了吗?简单吧,哈哈。

JSONP又是什么呢?JSON应该大家都比较熟悉了,在AJAX程序传递数据时替代XML的佳品,还有不清楚的同学猛击这里了
解更多。JSONP的全称是JSON with
padding,大概是JSON前面加了点东西的的意思吧,哈哈。其实解决这个跨域问题和JSON一点关系都没有的,但因为他的简洁、优
雅,google、yahoo这些大佬的很多服务都使用了他来作为数据传递的格式,所以JSONP也成了解决跨域数据传递的一个标准吧。

使用JSONP的具体方法时,在创建的script标签src属性中,使用一个callback参数标识当前脚本的一个回调方法,回调方法的参数是一JSON格式对象。站外的程序处理完毕后,就输出一段调用这个回调方法的脚本,非常简洁!

基本上原理就是这样了,这个东东我是在研究GWT时才去了解的,参考:http://code.google.com/webtoolkit/tutorials/1.6/Xsite.html#request
网上的例子也很多,我就懒得做了,可以参考:
Google的:http://code.google.com/apis/gdata/json.html#Request
yahoo!的:http://developer.yahoo.net/forum/index.php?s=828eca07dbd1c1607c2bddc5b5832261&showtopic=100

以下是从雅虎摘录的一篇文件,虽然不是讲解jsonp但是涉及到了

Today we announced an update to GeoPlanet that adds a few new features. This topic provides information about each of these new features and examples for using them.

1) New "callback" query parameter

The callback parameter is used with the JSON response format (and new GeoJSON response format) to implement JSONP. The callback parameter is a JavaScript function name that will be prepended to the JSON data (along with surrounding parentheses). This allows a GeoPlanet request to be used as the src parameter for a <script> tag and execute a previously defined JavaScript function.

Example:

The request http://where.yahooapis.com/v1/place/12521721?appid=[yourappid]&format=json&callback=myfunc returns the following:

myfunc({"places":{"place":[{"woeid":12521721,"placeTypeName":"Airport","placeTypeName attrs":{"code":14},
"name":"San Francisco International Airport","country":"United States","country attrs":{"type":"Country","code":"US"},
"admin1":"California","admin1 attrs":{"type":"State","code":"US-CA"},
"admin2":"San Mateo","admin2 attrs":{"type":"County","code":""},
"admin3":"","locality1":"Millbrae","locality1 attrs":{"type":"Town"},"locality2":"",
"postal":"94128","postal attrs":{"type":"Zip Code"},"centroid":{"latitude":37.614712,"longitude":-122.391808},
"boundingBox":{"southWest":{"latitude":37.601822,"longitude":-122.408089},
"northEast":{"latitude":37.627602,"longitude":-122.375526}},
"uri":"http://where.yahooapis.com/v1/place/12521721","lang":"en-us"}],"start":0,"count":1,"total":1}});


This can be included in an HTML document:

<script src="http://where.yahooapis.com/v1/place/12521721?appid=[yourappid]&format=json&callback=myfunc"></script>

2) New "GeoJSON" response format

The GeoJSON response format returns geographic information using tags defined by draft version 6 of the GeoJSON specification. In particular,all place resources are defined as Point types,the place centroid is returned in the coordinates element,and the place bounding box is returned in the bbox element.

Example:

The request http://where.yahooapis.com/v1/place/12521721?appid=[yourappid]&format=geojson returns the following:

{"places":{"place":[{"woeid":12521721,"type":”Point”,”coordinates”:[-122.391808,37.614712],
"bbox":[-122.408089,37.601822,-122.375526,37.627602],"total":1}}


3) New $and filter for /places collection

The $and filter allows two other filters to be provided for requests for the /places collection. This means that a request can filter by place type as well as by place name. The $and filter takes two arguments that are filters themselves.

Example:

The request http://where.yahooapis.com/v1/places$and(.q(Long+Island),.type(Town));count=0?appid=[yourappid] returns all places named “Long Island” that are towns.

Multiple place types can be provided. For example:

The request http://gws1.dev01.maps.sp1.yahoo.com/v1/places$and(.q(Long+Island),.type(Town,Suburb));count=0?appid=[yourappid] returns all places named “Long Island” that are towns or suburbs.

4) New placetype resource

The placetype resource allows information to be returned about a single place type. This resource can simplify applications that want to use place type information.

Example:

The request http://where.yahooapis.com/v1/placetype/10)?appid=[yourappid] returns the following:

<placeType yahoo:uri="http://where.yahooapis.com/v1/placetype/10" xml:lang="en-us">
<placeTypeName code="10">Local Administrative Area</placeTypeName>
</placeType>


5) Long description for placetype resource (and placetypes collection)

The placeType resource now has a long representation that includes a one line description for the place type. This can help users understand how the place type is used. The long representation can be selected for the placetypes collection as well.

Example:

The request http://where.yahooapis.com/v1/placetype/10)?appid=[yourappid]&select=long returns the following:

<placeType yahoo:uri="http://where.yahooapis.com/v1/placetype/10" xml:lang="en-us">
<placeTypeName code="10">Local Administrative Area</placeTypeName>
<placeTypeDescription>One of the tertiary administrative areas within a country</placeTypeDescription>
</placeType>


We hope you find these new features useful. If you have suggestions for improving GeoPlanet,please let us know!

Eddie Babcock
Principal Engineer,Yahoo! Geo Technologies
============================以下是从google摘录的一篇文章================================================

JSONP

From Wikipedia,the free encyclopedia
Jump to: navigation,search

JSONP or "JSON with padding" is a complement to the base JSON data format. It provides a method to request data from a server in a different domain,something prohibited by typical web browsers because of the Same origin policy.

Under the same origin policy,a web page served from server1.example.com cannot normally connect to or communicate with a server other than server1.example.com. An exception is the HTML <script> element. Exploiting the open policy for <script> elements,some pages use them to retrieve JavaScript code that operates on dynamically generated JSON-formatted data from other origins. This usage pattern is known as JSONP. Requests for JSONP retrieve not JSON,but arbitrary JavaScript code. They are evaluated by the JavaScript interpreter,not parsed by a JSON parser.

There have been some criticisms raised to JSONP. Cross-Origin Resource Sharing is a more recent method of getting data from a server in a different domain,which addresses some of those criticisms.

Contents

[hide]
  • 1 How it works
  • 2 Padding
  • 3 Script element injection
  • 4 Security concerns
    • 4.1 Cross-site request forgery
  • 5 History
  • 6 References
  • 7 External links

[edit] How it works

To see how this pattern works,first consider a URL which on request returns a JSON document. A JavaScript program might request this URL via XMLHttpRequest,for example. Suppose a URL is http://server2.example.com/RetrieveUser?UserId=xxx. Suppose the UserId of Foo is 1234. A browser requesting the URL http://server2.example.com/RetrieveUser?UserId=1234,passing the UserId of Foo,might receive something like:

   {"Name": "Foo", "Id" : 1234, "Rank": 7}

This JSON data could be dynamically generated,according to the query parameters passed in the URL.

Now imagine specifying a URL that returns JSON as the src attribute for a <script> element. The problem with this is that the JSON is evaluated as JavaScript,but instead of interpreting the content as object literal,it would be interpreted as a block and throw a syntax error. Even if it was correctly interpreted as object literal,it cannot be accessed by JavaScript as it is not assigned to a variable.

In the JSONP usage pattern,the src attribute in the <script> element returns dynamically generated JSON,with a function call wrapped around it. In this way,the returned resource is still legal JavaScript,but because the anonymous object literal is wrapped in a function call,the browser's JavaScript environment can act on the returned data. It might look like this:

   functionCall({"Name": "Foo", "Rank": 7});

The function call is the "P" of JSONP - the "padding" around the pure JSON,or according to some[1] the "prefix". By convention,the browser provides the name of the callback function as a named query parameter,typically using the name jsonp or callback,in its request to the server,e.g.,

 <script type="text/javascript"
 src="http://server2.example.com/RetrieveUser?UserId=1234&jsonp=parseResponse">
 </script>

In this example,the received payload would be:

   parseResponse({"Name": "Foo", "Rank": 7});

[edit] Padding

While the padding (prefix) is typically the name of a callback function that is defined within the execution context of the browser,it may also be a variable assignment,an if statement,or any other JavaScript statement. The response to a JSONP request (namely,a request following the JSONP usage pattern) is not JSON and is not parsed as JSON; the returned payload can be any arbitrary JavaScript expression,and it does not need to include any JSON at all. But conventionally,it is a JavaScript fragment that invokes a function call on some JSON-formatted data.

Said differently,the typical use of JSONP provides cross-domain access to an existing JSON API,by wrapping a JSON payload in a function call.

[edit] Script element injection

JSONP makes sense only when used with a script element. For each new JSONP request,the browser must add a new <script> element,or reuse an existing one. The former option - adding a new script element - is done via dynamic DOM manipulation,and is known as script element injection. The <script> element is injected into the HTML DOM,with the URL of the desired JSONP endpoint set as the "src" attribute. This dynamic script element injection is usually done by a javascript helper library. jQuery and other frameworks have JSONP helper functions; there are also standalone options. [2]

The dynamically injected script element for a jsonp call looks like this:

 <script type="text/javascript"
 src="http://server2.example.com/RetrieveUser?UserId=1234&jsonp=parseResponse">
 </script>

After the element is injected,the browser evaluates the element,and performs an HTTP GET on the src URL,retrieving the content. Then the browser evaluates the return payload as javascript. This is typically a function invocation.

In that way,the use of JSONP can be said to allow browser pages to work around the same origin policy via script element injection.

[edit] Security concerns

Including script tags from remote sites allows the remote sites to inject any content into a website. If the remote sites have vulnerabilities that allow JavaScript injection,the original site is exposed to an increased risk.

An effort is underway to define a safer strict subset definition for JSON-P[3] that browsers would be able to enforce on script requests with a specific MIME-type such as "application/json-p". If the response didn't parse as strict JSON-P,the browser could throw an error or just ignore the entire response. For the moment however the correct MIME-type is "application/javascript" for JSONP.

[edit] Cross-site request forgery

Naive deployments of JSONP are subject to cross-site request forgery (CSRF or XSRF) attacks.[4] Because the HTML <script> tag does not respect the same origin policy in web browser implementations,a malicious page can request and obtain JSON data belonging to another site. This will allow the JSON-encoded data to be evaluated in the context of the malicious page,possibly divulging passwords or other sensitive data if the user is currently logged into the other site.

This is problematic only if the JSON-encoded data contains sensitive information which should not be disclosed to a third party,and the server depends on the browser's Same Origin Policy to block the delivery of the data in the case of an improper request. There is no problem if the server determines the propriety of the request itself,only putting the data on the wire if the request is proper. Cookies are not by themselves adequate for determining if a request was authorized. Exclusive use of cookies is subject to cross-site request forgery.

[edit] History

In July 2005 George Jempty suggested an optional variable assignment be prepended to JSON.[5][6] The original proposal for JSONP,where the padding is a callback function,appears to have been made by Bob Ippolito in December 2005[7] and is now used by many Web 2.0 applications such as by Dojo Toolkit, Google Web Toolkit,[8] and Web services.

[edit] References

  1. ^ "Experimental RDF result set to JSON translator". http://epimorph-pubx1.appspot.com/help.html. Retrieved February 20,2012.
  2. ^ "example jsonp library on pastebin". http://pastebin.com/ADxHdCnB.
  3. ^ "Safer cross-domain Ajax with JSON-P/JSONP". JSON-P.org. http://www.json-p.org/. Retrieved 30 October 2011.
  4. ^ Grossman,Jeremiah (January 27,2006). "Advanced Web Attack Techniques using GMail". http://jeremiahgrossman.blogspot.com/2006/01/advanced-web-attack-techniques-using.html. Retrieved July 3,2009.
  5. ^ "eval'ing JSON". July 19,2005. http://replay.web.archive.org/20060212113746/http://htmatters.net/htm/1/2005/07/evaling-JSON.cfm.
  6. ^ "json: Message: Re: Comments". August 17,2005. http://tech.groups.yahoo.com/group/json/message/82.
  7. ^ "Remote JSON - JSONP". from __future__ import *. Bob.pythonmac.org. December 5,2005. http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/. Retrieved September 8,2008.
  8. ^ "GWT Tutorial: How to Read Web Services Client-Side with JSONP". Google Web Toolkit Applications. February 6,2008. http://www.gwtapps.com/?p=42. Retrieved July 3,2009.

[edit] External links

  • Official website
  • About JSONP in JavaScript
  • jsonp-java wraps any response content into a jsonp callback
  • An implementation of a JSONP utility class

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读