Cross-domain articles --JSONP principle

An article so that you understand the principle Detailed jsonp

What is JSONP?

 

Let us talk about how JSONP is generated:

 

In fact, the Internet has a lot to explain about JSONP, but stereotyped, and foggy, for many people new to speaking difficult to interpret, with their own way to explain this issue to see if that helps.

 

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 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<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 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<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":"我是远程js带来的数据"});

 

After running View Results, page successfully prompted window, displays the local function is a cross-domain remote js call succeeds, and also received the data from a remote js brings.


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 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<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?code=CA1998&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 called by a code parameter passed, I want to tell the server to check the time information is CA1998 flight, and callback parameter tells the server to my local callback function called flightHandler, so please pass this function the query results the call.

OK, the server is very clever, this is called flightResult.aspx page generation for a while this code to jsonp.html

(Implement the service here is not the end of the presentation, and your choice of language, in the final analysis is the string concatenation):

flightHandler({
    "code": "CA1998",
    "price": 1780,
    "tickets": 5
});

 

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 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<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, it is not so cool it?
supplement

Here to do some additional explanation for the similarities and differences ajax and jsonp:

. 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

 

Guess you like

Origin www.cnblogs.com/still1/p/11008134.html