jQuery.getJson 跨域访问资源

jquery.getJson()跨域

 

由于浏览器的同源特性限制(Same_origin_policy),这样js去访问非本域下的资源,使用平常的做法就不会实现了。

 

要想完成跨域访问资源传统上有三个方法:

 

 写道
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".

 

 还有另外一种实现方法就是jsonp(json + padding )

 

 写道
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.

 

 

jQuery中的getJson就是使用这样的方法实现的,当然$.ajax方法也可以完成,这是jQuery的ajax最终高调用方法

 

使用getJson完成跨域操作需要客户端与服务器端两部分共同协作

 

客户端:js

 

 写道
JSONP
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

 

 

即在getJson的url参数末尾加个callback=?这样的参数

 

$.getJson('http://other-domain.com/get_json_data.htm?callback=?', function(data) {
    alert(data);
});

 

 

服务器:java(struts2)

在正常的ajax返回数据的参数配置上多添加一个参数

callbackParameter,同时指定客户端传递过来的参数callback

 

 

<result  type=”json”>
  <param name=”callbackParameter”>callback</param>
</result>

 

原理是,在客户端类似生成一个<script type=“text/javascript”>callback(data);</script>这样一个在客户端执行的一个js代码片段。

 

 

 

[1]http://api.jquery.com/jQuery.getJSON/

[2]http://api.jquery.com/jQuery.ajax/

[3]http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/

[4]http://www.iteye.com/problems/45157

[5]http://www.iteye.com/problems/47527

[6]http://www.yindaoxian.com/html/web/Javascript_Ajax-13610.html

[7]http://en.wikipedia.org/wiki/Same_origin_policy

[8]http://lyzdz.com/index.php/archives/52

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值