jsonp, easy to understand

What is JSONP?

Baidu look casually on the site, there are a lot of explaining about JSONP, but it feels like a whole, and after reading many still stupefied, for many people who are new to JSONP still difficult to understand, try to use their own language to talk about JSONP, see if it helps you.

First, let us talk about how JSONP is generated:

1, a well-known problem, Ajax direct cross-domain request without access to a common file problems, no matter you are static pages, dynamic web pages, web services, WCF, as long as the cross-domain requests, will be allowed.

2, but we also found that the impact of cross-domain is not whether you call js file on a Web page (Not only that, we also found that those who have the "src" attribute of the tags have the ability to cross-domain, such as <\ script> , <\ img>, <\ iframe>).

3, so you can judge by the current stage if you want to end the pure web (ActiveX Controls, proxy server, the future belongs to HTML5 is not the Websocket etc.) accessing data across domains is only one possible, that is to try on a remote server js file loaded into the data format, the client calls and for further processing.

4, as it happens we already know there is something called pure character JSON data format concise description of complex data, even better is also js native JSON support, so this format of the data processing on the client side can be almost arbitrary.

5, with such solutions ready to come up, web client by calling the script exactly the same way, to call js file format dynamically generated on cross-domain server (generally JSON suffix), it is obvious why the server to dynamically generate JSON document, the purpose is to load data into the client needs.

6, the client after the call to the success of the JSON file, also obtained data they need, the rest is processed in accordance with their needs and show that this way of remote data acquisition looks very much like AJAX, but in fact not the same.

7, in order to facilitate the use of the client data, gradually formed an informal transport protocol, it JSONP call it, a point of the protocol is to allow users to pass a callback parameter to the server, the server would then return the data when the callback function name as a parameter to wrap the JSON data so that clients can freely customize their function to automatically process the returned data.

If you how to use some vague parameters for a callback, then we will have specific examples to explain later.

JSONP client specific implementation:

Regardless of jQuery Ye Hao, extjs worth mentioning, or other support jsonp framework of the work done behind the scenes they are the same, Let me explain step by step to achieve the client's jsonp:

1, we know that, even if cross-domain file js code (of course, means a web scripting security policy), web pages can also be executed unconditionally.

There are at the root of a remote server remoteserver.com remote.js file code is as follows:

alert('我是远程文件');

There under a local server localserver.com jsonp.html page code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
    <script type="text/javascript" src="http://remoteServer.com/remote.js"></script>
</head>
<body>
 
</body>
</html>

Undoubtedly, the page will pop up a prompt window, showing the success of cross-domain calls.

2. Now we define a function, and then call in the incoming data in remote remote.js jsonp.html page.

jsonp.html page code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
    <script type="text/javascript">
    var localHandler = function(data){
        alert('我是本地函数,可以被跨域的remote.js文件调用,远程js带来的数据是:' + data.result);
    };
    </script>
    <script type="text/javascript" src="http://remoteserver.com/remote.js"></script>
</head>
<body>
 
</body>
</html>

remote.js document code is as follows:

localHandler ({ "result": "I was brought js remote data"});
see the results after the operation, the page successfully prompted window, displays the local function is a cross-domain remote js call succeeds, and also received with a remote js to the data.
Very pleased, the purpose of cross-domain remote access to data basically achieved, but it is a problem, how do I let the remote js function it should call the local know What is the name of it? After all, the service is jsonp who have to face a lot of clients, and these serve their local functions are not the same ah? We then look down.

3, smart developers can easily think of, as long as js script server provides is dynamically generated on the line chanting, so the caller can pass a parameter in the past to tell the server "I want some call js code XXX function, you return to me ", so the server can in accordance with the needs of the client to generate js script and responded to.

Look at the code jsonp.html page:

<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
    <script type="text/javascript">
    // 得到电影信息查询结果后的回调函数
    var flightHandler = function(data){
        alert('你查询的电影结果是:票价 ' + data.price + ' 元,' + '余票 ' + data.tickets + ' 张。');
    };
    // 提供jsonp服务的url地址(不管是什么类型的地址,最终生成的返回值都是一段javascript代码)
    var url = "http://flightQuery.com/jsonp/flightResult.aspx?time=12m12d&callback=flightHandler";
    // 创建script标签,设置其属性
    var script = document.createElement('script');
    script.setAttribute('src', url);
    // 把script标签加入head,此时调用开始
    document.getElementsByTagName('head')[0].appendChild(script); 
    </script>
</head>
<body>
 
</body>
</html>

This code change is relatively large, no longer write directly to the remote js file dead, but Coding dynamic query, and this is what jsonp client implementation of the core part, the focus in this case is how to do it is to call jsonp the whole process.
We see the url call parameters passed a time, I want to tell the server to check the information on the 12th day of December, while the callback parameter tells the server to my local callback function called flightHandler, so please pass the query results this function call.
OK, the server is very clever, this is called flightResult.aspx page generation for a while this code to jsonp.html:

flightHandler({
    "time": "12m12d",
    "price": 39,
    "tickets": 16
});

4. Up to this point, I believe that you have been able to understand jsonp client implementation principle, right? The rest is about how the code package, in order to interact with the user interface, enabling multiple and repeated calls

JQuery how to achieve jsonp call?

<!DOCTYPE html>
<html lang="en">
<head>
     <title>Untitled Page</title>
      <script type="text/javascript" src=jquery.min.js"></script>
      <script type="text/javascript">
     jQuery(document).ready(function(){ 
        $.ajax({
             type: "get",
             async: false,
             url: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998",
             dataType: "jsonp",
             jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
             jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
             success: function(json){
                 alert('您查询到电影信息:票价: ' + json.price + ' 元,余票: ' + json.tickets + ' 张。');
             },
             error: function(){
                 alert('fail');
             }
         });
     });
     </script>
     </head>
  <body>
  </body>
</html>

Is not it strange? Why this time I did not write flightHandler this function? And surprisingly successful operation!
This is a credit to the jQuery, jquery when dealing jsonp type of ajax (, although the jsonp jquery also included in the ajax, but in fact they are really not the same thing children), automatic callback and help you generate the data taken out property method to call for success, is not so cool it?
supplement

Finally, ajax and jsonp similarities and differences added:

. 1, and jsonp ajax on these two technologies is called "look" like an object, too, is a request url, then the server returns the data is processed, and therefore jquery jsonp regarded as a frame. Ext ajax one form of package.

2, but the ajax and jsonp actually something different nature. Ajax is to acquire non-core content on this page by XmlHttpRequest, while the core is dynamically added jsonp

Published 10 original articles · won praise 0 · Views 318

Guess you like

Origin blog.csdn.net/qq_30627241/article/details/104848405