jsonp 是如何工作的

JSONP是一种从不同domain获取JSON数据的方式,它不会受到像XMLHttpRequest在浏览器中的同源策略限制。jQuery.getJson()自动切换到JSONP模式。

<script>
function processJSON (json) {
  // Do something with the JSON response
};
</script>

<script src='http://api.flickr.com/services/feeds/photos_public.gne?
jsoncallback=processJSON&tags=monkey&tagmode=any&format=json'></script>
  • processJSON是我们自己定义的一个JavaScript函数
  • jsoncallback=processJSON和后面的key=value对将会告诉服务器,response该如何返回,服务器也应该支持这种请求URL

发送到服务器之后,服务器会返回如下的字符串:

processJSON( {
    "title": "Recent Uploads tagged monkey",
    "link": "http://www.flickr.com/photos/tags/monkey/",
    "description": "",
    "modified": "2015-02-03T21:23:22Z",
    "generator": "http://www.flickr.com/",
    "items": [ 
        // ... Much more JSON here ...
    ]
} )

最后因为script标签不受浏览器的同源策略限制,结果也会被自然而然的执行。你可以称这种模式为callback pattern

分析过程

JSONP的核心是:

    1. 一个在你网站上定义的callback function
    1. 一个通过<script>标签实现的请求
    1. 一个response

异步

为了使代码执行的时候,不会阻塞整个页面,我们可以这样做:

<script>
function processJSON (json) {
  // Do something with the JSON response
};

// Create a new script element
var script_element = document.createElement('script');

// Set its source to the JSONP API
script_element.src = 'http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=processJSON&tags=monkey&tagmode=any&format=json';

// Stick the script element in the page <head>
document.getElementsByTagName('head')[0].appendChild(script_element);
</script>

动态添加script在下载的时候,并不会阻塞其它组件。事实上,这就是jQuery.getJSON()幕后所发生的事情;XMLHttpResult从来没有参与JSONP的整个调用过程。事实上,jQueryJSONP比我们这里介绍的当然要复杂一些,但现在你已经基本了解了这些技巧。

So how does JSONP really work?

results matching ""

    No results matching ""