`
Joson_Coney
  • 浏览: 57224 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Remote JSON - JSONP

 
阅读更多

( From : http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/ )

Remote JSON - JSONP

December 05, 2005 at 08:21 PM | categories: AJAXjavascriptMochiKit | 15 Comments

 

The browser security model dictates that XMLHttpRequest, frames, etc. must have the same domain in order to communicate. That's not a terrible idea, for security reasons, but it sure does make distributed (service oriented, mash-up, whatever it's called this week) web development suck.

There are traditionally three solutions to solving this problem.

Local proxy:
Needs infrastructure (can't run a serverless client) and you get double-taxed on bandwidth and latency (remote - proxy - client).
Flash:
Remote host needs to deploy a crossdomain.xml file, Flash is relatively proprietary and opaque to use, requires learning a one-off moving target programming langage.
Script tag:
Difficult to know when the content is available, no standard methodology, can be considered a "security risk".

I'm proposing a new technology agnostic standard methodology for the script tag method for cross-domain data fetching: JSON with Padding, or simply JSONP.

The way JSONP works is simple, but requires a little bit of server-side cooperation. Basically, the idea is that you let the client decide on a small chunk of arbitrary text to prepend to the JSON document, and you wrap it in parentheses to create a valid JavaScript document (and possibly a valid function call).

The client decides on the arbitrary prepended text by using a query argument named jsonp with the text to prepend. Simple! With an empty jsonp argument, the result document is simply JSON wrapped in parentheses.

Let's take the del.icio.us JSON API as an example. This API has a "script tag" variant that looks like this:

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

if(typeof(Delicious) == 'undefined') Delicious = {}; Delicious.posts = [{ "u": "http://mochikit.com/examples/interpreter/index.html", "d": "Interpreter - JavaScript Interactive Interpreter", "t": [ "mochikit","webdev","tool","tools", "javascript","interactive","interpreter","repl" ] }]

In terms of JSONP, a document semantically identical to this would be available at the following URL:

http://del.icio.us/feeds/json/bob/mochikit+interpreter?jsonp=if(typeof(Delicious)=='undefined')Delicious={};Delicious.posts=

That's not very interesting on its own, but let's say I wanted to be notified when the document is available. I could come up with a little system for tracking them:

var delicious_callbacks = {}; function getDelicious(callback, url) { var uid = (new Date()).getTime(); delicious_callbacks[uid] = function () { delete delicious_callbacks[uid]; callback(); }; url += "?jsonp=" + encodeURIComponent("delicious_callbacks[" + uid + "]"); // add the script tag to the document, cross fingers }; getDelicious(doSomething, "http://del.icio.us/feeds/json/bob/mochikit+interpreter");

The fetched URL from this hypothetical experiment would look something like this:

http://del.icio.us/feeds/json/bob/mochikit+interpreter?jsonp=delicious_callbacks[12345]

delicious_callbacks[12345]([{ "u": "http://mochikit.com/examples/interpreter/index.html", "d": "Interpreter - JavaScript Interactive Interpreter", "t": [ "mochikit","webdev","tool","tools", "javascript","interactive","interpreter","repl" ] }])

See, because we're wrapping with parentheses, a JSONP request can translate into a function call or a plain old JSON literal. All the server needs to do differently is prepend a little bit of text to the beginning and wrap the JSON in parentheses!

Now, of course, you'd have libraries like MochiKitDojo, etc. abstracting JSONP so that you don't have to write the ugly DOM script tag insertion yourself, etc.

Of course, this just solves the standardization problem. Your page is still toast if the remote host decides to inject malicious code instead of JSON data. However, if implemented, it'd save a lot of developers some time and allow for generic abstractions, tutorials, and documentation to be built.


分享到:
评论

相关推荐

    Silverlight通过json-rpc交互数据

    在Silverlight应用中,与服务器的数据交互是必不可少的,而json-rpc(JSON Remote Procedure Call)则提供了一种轻量级的、高效的通信方式。 **一、理解json-rpc** json-rpc是一种基于JSON(JavaScript Object ...

    JSON和JSONP(含jQuery实例)

    JSON(JavaScript Object Notation)是一...至于`RemoteService`,这可能是服务端提供的一个接口名称,用于提供JSON或JSONP数据服务。在实际项目中,开发者可能需要根据这个接口来构建前端请求,获取并处理返回的数据。

    ispconfig-json-wrapper:这是 ISPConfig 远程 API 的 JSONJSONP 包装器

    安装以 root 身份,将这两个文件复制到 ISPConfig 文档...只需添加一个回调查询参数即可触发 JSONP要求JSON 请求是普通的表单编码 POST 请求,其方法是作为 URL 查询参数执行的,名为 method(即 /remote/json.php?meth

    ScanEvent:票据扫描应用

    http://bob.ippoli.to/archives/2005/12/05/remote-json-jsonp/ http://api.jquery.com/jQuery.ajax/ http://en.wikipedia.org/wiki/JSONP ...

    使用jsonrpc

    JSON-RPC(JavaScript Object Notation Remote Procedure Call)是一种轻量级的远程过程调用协议,主要应用于客户端与服务器之间的通信,特别是在Web服务中。它的设计灵感来源于XML-RPC,但采用了JSON作为数据交换...

    jqGrid:四、 remote data(JSON)

    **jqGrid:四、remote data (JSON)** jqGrid是一款基于jQuery的开源表格插件,它提供了丰富的功能,包括数据网格展示、编辑、排序、筛选等。在远程数据(remote data)模式下,jqGrid能够从服务器获取JSON格式的...

    javascriptRPC

    例如,JSONP(JSON with Padding)是一种常见的跨域RPC解决方案,通过动态创建`<script>`标签来加载返回JSON数据的服务器脚本。 现代JavaScript RPC的实现更多地依赖于WebSocket,它提供了全双工、低延迟的通信通道...

    jquery电子文档chm

    As of jQuery 1.2, you can load JSON data located on another domain if you specify a JSONP callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct ...

    jQuery中JSONP的两种实现方式详解

    $.get('http://example.com/remoteService?name=jxq&email=feichexia@yahoo.com.cn&jsonpcallback=?', function(json) { console.log(json.Name); console.log(json.Email); }); ``` 在这种情况下,服务器仍然...

    dwr推模式应用—异步实现页面数据添加

    -- WARNING: 允许JSON-RPC连接会绕过DWR提供的大部分安全保护,请谨慎使用 --> <init-param> <param-name>jsonRpcEnabled</param-name> <param-value>true</param-value> </init-param> <!-- WARNING: 允许...

    Jquery跨域Ajax请求测试

    JSONP(JSON with Padding)是一种规避同源策略的方法,它通过动态创建 `<script>` 标签来加载服务端返回的JavaScript代码,该代码会调用一个预先定义好的回调函数并传递数据。 以下是一个简单的jQuery跨域Ajax请求...

    Jquery 的Ajax 用法

    例如,当涉及到跨域请求时,JQuery 会利用 `<script>` 标签的特性,以 JSONP(JSON with Padding)的方式实现跨域数据交换。 在处理返回的数据时,JQuery 提供了 `success` 回调函数,可以在数据成功返回后进行处理...

    jquery-easyui

    - **JSONP(JSON with Padding)**:跨域数据获取策略,适用于不支持 CORS 的情况。 - **AJAX**:无刷新地与服务器交换数据,实现页面部分更新。 4. **事件处理** - **事件监听(Event Handling)**:绑定各种组件的...

    jQuery实现跨域

    然而,为了实现数据交互,开发者们发明了各种跨域解决方案,其中jQuery库中的JSONP(JSON with Padding)就是一种常用的解决方式。本文将详细介绍如何使用jQuery实现跨域,以及其工作原理。 首先,我们要理解JSONP...

    java web中调用后台方法用js快速生成图表

    这些方法通常会从数据库或其他数据源获取数据,然后将其转化为适合图表展示的格式,如JSON。 3. **DWR接口暴露**: - 在`dwr.xml`中,声明刚刚创建的Java类和方法,使得它们可以通过DWR被JavaScript调用。 4. **...

    ext分页客户端demo Java js

    - 使用EXTJS的远程分页(remote paging)模式,服务器根据`start`和`limit`返回对应数据,同时提供总记录数,以避免一次性加载大量数据。 6. **实际项目应用**: - 在实际项目中,可以将这个分页示例作为基础,...

    详解vue-cli项目中的proxyTable跨域问题小结

    JSONP (JSON with Padding) JSONP 是一种古老的跨域解决方案,它利用 `<script>` 标签不受同源策略限制的特点。JSONP 的核心是动态创建 `<script>` 标签,并设置 `src` 属性指向跨域的 API 接口,同时提供一个回调...

Global site tag (gtag.js) - Google Analytics