Home  >  Article  >  Web Front-end  >  5 solutions to js cross-domain requests_javascript skills

5 solutions to js cross-domain requests_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:52:001132browse

The solutions for cross-domain request data mainly include the following solutions:

JSONP方式
表单POST方式
服务器代理
Html5的XDomainRequest
Flash request

Separate instructions:

1. JSONP:

Intuitive understanding:

It is to dynamically register a function on the client

function a(data), and then pass the function name to the server, and the server returns an a({/*json*/}) to the client to run, thus calling the client's

function a(data), thus achieving cross-domain.

Birth background:

1. Ajax directly requests ordinary files, which has the problem of cross-domain access without permission. Regardless of whether it is a static page, dynamic web page, web service, or wcf, as long as it is a cross-domain request, it will not work.

2. However, when calling js files on the web page, it is not affected by this

3. Further promotion, we found that all tags with Src attributes have cross-domain capabilities, such as: 3f1c4e4b6b16bbbd69b2ee476dc4f83aa1f02c36ba31691bcfe87b2722de723bd5ba1642137c3f32f4f4493ae923989c

4. Therefore, if you currently want to access data cross-domain through the pure web side (ActiveX controls, server-side proxies, Websockets belonging to the future HTML5, etc. are not included), you can only use the following method: on the remote server Try to load the data into text in js format for client calling and further processing.

5. JSON is a pure character data format and can be natively supported by js.

6. Here is the solution: the web client calls the dynamically generated js format file (usually with json as the suffix) on the cross-domain server in exactly the same way as calling the script.

7. After the client successfully calls the json file, it will get the required data, and the rest is to process it according to its own needs.

8 In order to facilitate the client to use data, an informal transmission protocol has gradually formed, called jsonp. A key point of this protocol is to allow users to pass a callback parameter to the server, and then when the server returns data, it will use this callback parameter as a function name to wrap the json data, so that the client can customize its own function to process the returned data.

Detailed implementation:

Whether it is jQuery, extjs, or other frameworks that support jsonp, the work they do behind the scenes is the same. Let me explain the implementation of jsonp on the client step by step:

1. We know that even if the code in the cross-domain js file (which of course complies with the web script security policy), the web page can be executed unconditionally.

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

alert('I am a remote file');

The local server localserver.com has a jsonp.html page code 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>

There is no doubt that a prompt window will pop up on the page, showing that the cross-domain call is successful.

2. Now we define a function on the jsonp.html page, and then call it by passing in data in remote.js.

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>

The remote.js file code is as follows:

localHandler({"result":"I am the data brought by remote js"});
Check the results after running. The page successfully pops up a prompt window, showing that the local function was successfully called by the cross-domain remote js, and the data brought by the remote js was also received. I am very happy that the purpose of cross-domain remote data acquisition has been basically achieved, but another question arises. How do I let the remote js know the name of the local function it should call? After all, jsonp servers have to face many service objects, and the local functions of these service objects are different? Let's look down.

3. Smart developers can easily think that as long as the js script provided by the server is dynamically generated, the caller can pass a parameter to tell the server "I want a js code that calls the XXX function , please return it to me", so the server can generate js scripts and respond according to the client's needs.

Look at the code of the 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&#63;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 time the code has changed a lot. It no longer directly writes the remote js file, but codes to implement dynamic query. This is also the core part of the jsonp client implementation. The focus in this example is how to Complete the entire process of jsonp calling.

We see that a code parameter is passed in the calling URL, telling the server that what I want to check is the information of flight CA1998, and the callback parameter tells the server that my local callback function is called flightHandler, so please pass the query results Call this function.

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

我们看到,传递给flightHandler函数的是一个json,它描述了航班的基本信息。运行一下页面,成功弹出提示窗口,jsonp的执行全过程顺利完成!

4、到这里为止的话,相信你已经能够理解jsonp的客户端实现原理了吧?剩下的就是如何把代码封装一下,以便于与用户界面交互,从而实现多次和重复调用。

什么?你用的是jQuery,想知道jQuery如何实现jsonp调用?好吧,那我就好人做到底,再给你一段jQuery使用jsonp的代码(我们依然沿用上面那个航班信息查询的例子,假定返回jsonp结果不变):

OK,服务器很聪明,这个叫做flightResult.aspx的页面生成了一段这样的代码提供给jsonp.html(服务端的实现这里就不演示了,与你选用的语言无关,说到底就是拼接字符串):

<!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&#63;code=CA1998",
       dataType: "jsonp",
       jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
       jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"&#63;",jQuery会自动为你处理数据
       success: function(json){
         alert('您查询到航班信息:票价: ' + json.price + ' 元,余票: ' + json.tickets + ' 张。');
       },
       error: function(){
         alert('fail');
       }
     });
   });
   </script>
   </head>
 <body>
 </body>
 </html>

是不是有点奇怪?为什么我这次没有写flightHandler这个函数呢?而且竟然也运行成功了!哈哈,这就是jQuery的功劳了,jquery在处理jsonp类型的ajax时(还是忍不住吐槽,虽然jquery也把jsonp归入了ajax,但其实它们真的不是一回事儿),自动帮你生成回调函数并把数据取出来供success属性方法来调用,是不是很爽呀?

以上所述就是本文的全部内容了,希望大家能够喜欢。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn