`

jQuery.getJson 跨域访问资源

    博客分类:
  • Web
阅读更多

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

 

 

 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics