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

使用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

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]

[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

[edit] External links

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


文章浏览阅读2.4k次。最近要优化cesium里的热力图效果,浏览了网络上的各种方法,发现大多是贴在影像上的。这么做好是好,但是会被自生添加的模型或者其他数据给遮盖。其次是网上的方法大多数是截取成一个矩形。不能自定义的截取自己所需要的。经过尝试,决定修改下cesium heatmap,让他达到我们需要的要求。首先先下载 cesium heatmap包。其中我们可以看到也是通过叠加entity达到添加canvas的方法绘制到地图上。我们先把这一段代码注释} else {} };
文章浏览阅读1.2w次,点赞3次,收藏19次。在 Python中读取 json文件也可以使用 sort ()函数,在这里我介绍一个简单的示例程序: (4)如果我们想将字符串转换为列表形式,只需要添加一个变量来存储需要转换的字符串即可。在上面的代码中,我们创建了一个名为` read`的对象,然后在文件的开头使用`./`关键字来命名该对象,并在文件中定义了一个名为` json`的变量,并在其中定义了一个名为` json`的字段。比如,我们可以使用 read方法读取 json文件中的内容,然后使用 send方法将其发送到 json文件中。_python怎么读取json文件
文章浏览阅读1.4k次。首字母缩略词 API 代表应用程序编程接口,它是一种设备,例如用于使用编程代码发送和检索数据的服务器。最常见的是,该技术用于从源检索数据并将其显示给软件应用程序及其用户。当您访问网页时,API 的工作方式与浏览器相同,信息请求会发送到服务器,如何在 Windows PC 中手动创建系统还原点服务器会做出响应。唯一的区别是服务器响应的数据类型,对于 API,数据是 JSON 类型。JSON 代表 JavaScript Object Notation,它是大多数软件语言中 API 的标准数据表示法。_api是什么 python
文章浏览阅读802次,点赞10次,收藏10次。解决一个JSON反序列化问题-空字符串变为空集合_cannot coerce empty string ("") to element of `java.util.arraylist
文章浏览阅读882次。Unity Json和Xml的序列化和反序列化_unity json反序列化存储换行
文章浏览阅读796次。reader.readAsText(data.file)中data.file的数据格式为。使用FileReader对象读取文件内容,最后将文件内容进行处理使用。_a-upload 同时支持文件和文件夹
文章浏览阅读775次,点赞19次,收藏10次。fastjson是由国内的阿里推出的一种json处理器,由java语言编写,无依赖,不需要引用额外的jar包,能直接运行在jdk环境中,它的解析速度是非常之快的,目前超过了所有json库。提示:以下是引用fastjson的方法,数据未涉及到私密信息。_解析器用fastjson还是jackson
文章浏览阅读940次。【Qt之JSON文件】QJsonDocument、QJsonObject、QJsonArray等类介绍及使用_使用什么方法检查qjsondocument是否为空
文章浏览阅读957次,点赞34次,收藏22次。主要内容原生 ajax重点重点JSON熟悉章节目标掌握原生 ajax掌握jQuery ajax掌握JSON第一节 ajax1. 什么是ajaxAJAX 全称为,表示异步的Java脚本和Xml文件,是一种异步刷新技术。2. 为什么要使用ajaxServlet进行网页的变更往往是通过请求转发或者是重定向来完成,这样的操作更新的是整个网页,如果我们只需要更新网页的局部内容,就需要使用到AJAX来处理了。因为只是更新局部内容,因此,Servlet。
文章浏览阅读1.4k次,点赞45次,收藏13次。主要介绍了JsonFormat与@DateTimeFormat注解实例解析,文中通过示例代码介绍的非常详细,对大家的学习 或者工作具有一定的参考学习价值,需要的朋友可以参考下 这篇文章主要介绍了从数据库获取时间传到前端进行展示的时候,我们有时候可能无法得到一个满意的时间格式的时间日期,在数据库中显 示的是正确的时间格式,获取出来却变成了时间戳,@JsonFormat注解很好的解决了这个问题,我们通过使用 @JsonFormat可以很好的解决:后台到前台时间格式保持一致的问题,
文章浏览阅读1k次。JsonDeserialize:json反序列化注解,作用于setter()方法,将json数据反序列化为java对象。可以理解为用在处理接收的数据上。_jsondeserialize
文章浏览阅读2.7k次。labelme标注的json文件是在数据标注时产生,不能直接应用于模型训练。各大目标检测训练平台或项目框架均有自己的数据格式要求,通常为voc、coco或yolo格式。由于yolov8项目比较火热,故此本博文详细介绍将json格式标注转化为yolo格式的过程及其代码。_labelme json 转 yolo
文章浏览阅读790次,点赞26次,收藏6次。GROUP_CONCAT_UNORDERED(): 与GROUP_CONCAT类似,但不保证结果的顺序。COUNT_DISTINCT_AND_ORDERED(): 计算指定列的不同值的数量,并保持结果的顺序。COUNT_ALL_DISTINCT(): 计算指定列的所有不同值的数量(包括NULL)。AVG_RANGE(): 计算指定列的最大值和最小值之间的差异的平均值。JSON_OBJECT(): 将结果集中的行转换为JSON对象。COUNT_DISTINCT(): 计算指定列的不同值的数量。_mysql json 聚合
文章浏览阅读1.2k次。ajax同步与异步,json-serve的安装与使用,node.js的下载_json-serve 与node版本
文章浏览阅读1.7k次。`.net core`提供了Json处理模块,在命名空间`System.Text.Json`中,下面通过顶级语句,对C#的Json功能进行讲解。_c# json
文章浏览阅读2.8k次。主要介绍了python对于json文件的读写操作内容_python读取json文件
文章浏览阅读770次。然而,有时候在处理包含中文字符的Json数据时会出现乱码的情况。本文将介绍一种解决Json中文乱码问题的常见方法,并提供相应的源代码和描述。而某些情况下,中文字符可能会被错误地编码或解码,导致乱码的出现。通过适当地控制编码和解码过程,我们可以有效地处理包含中文字符的Json数据,避免乱码的发生。通过控制编码和解码过程,我们可以确保Json数据中的中文字符能够正确地传输和解析。为了解决这个问题,我们可以使用C#的System.Text.Encoding类提供的方法进行编码和解码的控制。_c# json 中文编码
文章浏览阅读997次。【代码】【工具】XML和JSON互相转换。_xml 转json
文章浏览阅读1.1k次。json path 提取数据_jsonpath数组取值
文章浏览阅读3w次,点赞35次,收藏36次。本文主要介绍了pandas read_json时ValueError: Expected object or value的解决方案,希望能对学习python的同学们有所帮助。文章目录1. 问题描述2. 解决方案_valueerror: expected object or value