Home  >  Article  >  Web Front-end  >  Detailed introduction to Javascript cross-domain knowledge

Detailed introduction to Javascript cross-domain knowledge

高洛峰
高洛峰Original
2016-11-05 16:37:281336browse

JS cross-domain knowledge summary:

Before the word "cross-domain" appeared frequently, we had actually used it frequently. For example, in the img of website A, the src points to a certain image address of website B. There is no doubt that this can be displayed normally under normal circumstances (regardless of the anti-hotlink technology); similarly, the src attribute of the script tag can be pointed to Script resources of other websites (in some cases this is even encouraged to take full advantage of the load of other websites and reduce the concurrency of your own server). However, if you use js to actively request data from other websites, such as ajax, you will encounter frustrating cross-domain problems, which is what we usually call cross-domain. Due to security reasons, cross-domain access is prohibited by default by major browsers. This involves the concept of the same-origin policy: the same-origin policy prevents scripts loaded from one domain from obtaining or manipulating document attributes on another domain. That is, the domain of the requested URL must be the same as the domain of the current web page. This means that the browser isolates content from different sources to prevent operations between them.

The blogger has not delved into the specific security issues brought about by cross-domain issues, so everyone can make up their own minds.

However, in many cases, especially today as the Internet continues to develop, we need to request front-end interfaces from different partners or data providers. Before the cross-domain access method was standardized (see the requirements for cross-domain access on the client side) This has also attracted the attention of w3c. According to the information, the HTML5 WebSocket standard supports cross-domain data exchange and should be an optional solution for cross-domain data exchange in the future). Is there any way to bypass its restrictions? There are many answers (although they are all troublesome), and the most commonly used one is the so-called JSONP cross-domain.

JSONP principle

The most basic principle of JSONP is: dynamically add a <script>标签,而script标签的src属性是没有跨域的限制的。这样说来,这种跨域方式其实与ajax XmlHttpRequest协议无关了。</script>

JSONP即JSON with Padding。由于同源策略的限制,XmlHttpRequest只允许请求当前源(域名、协议、端口)的资源。如果要进行跨域请求, 我们可以通过使用html的script标记来进行跨域请求,并在响应中返回要执行的script代码。 这种跨域的通讯方式称为JSONP。

来个简单的例子:

<!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>Test Jsonp</title>
  <script type="text/javascript">
      function jsonpCallback(result)
      {
      alert(result.msg);
      }
    </script>
<script type="text/javascript" src="http://crossdomain.com/jsonServerResponse?jsonp=jsonpCallback"></script>
</head>
<body>
</body>
</html>

Briefly describe the principle and process: first register a callback on the client, and then pass the name of the callback to the server (here the client and the server agree to pass the key as the query string value of jsonp). At this point, the server first generates json data. Then use javascript syntax to generate a function, and the function name is the passed parameter jsonp. Finally, the json data is placed directly into the function as a parameter, thus generating a js syntax document and returning it to the client. The client browser parses the script tag and executes the returned javascript document, that is, executing the predefined callback function.

It can be deduced from the above brief description: In addition to returning js code fragments in the form of functions, the server can naturally return all executable js fragments that meet the specifications.

The disadvantages of JSONP are: it only supports GET requests and not other types of HTTP requests such as POST; it only supports cross-domain HTTP requests and cannot solve the problem of how to make JavaScript calls between two pages in different domains . (Also below)

Jsonp of jQuery

As mentioned before, jsonp is not an ajax request, but jQuery still provides a method consistent with jQuery.ajax for cross-domain requests:

$.ajax({
  url: &#39;http://crossdomain.com/jsonServerResponse&#39;,
  type: &#39;GET&#39;,
  dataType: &#39;jsonp&#39;,
  jsonp: "callback",
  jsonpCallback: &#39;functionName&#39;,
  success: function (data, textStatus, jqXHR) { }
  //……
});

As shown above, dataType is set to jsonp. This is a cross-domain request. jsonp is set to the query string key predetermined by the server to pass the function name, and jsonpCallback is the js function name; if jsonpCallback is not set, jQuery will automatically generate a random function name (in the window object Load a global function, the function is executed when the code is inserted, and will be removed after execution). It can be inferred that the automatically generated function will call back the success function in the above code. (When manually assigning a value to jsonpCallback, I don’t know if the success function will call back, or will jQuery look for a predefined function, and report an error if it cannot be found? The blogger is lazy, and will try again later.) Of course, jQuery provides us with a The simple version, $.getJSON, will not be described here.

What needs to be noted is the jqXHR parameter in the success function. In an ajax request, it is an authentic jqXHR object, which can also be regarded as an XMLHTTPRequest object (inherited or encapsulated). However, this is not the case in jsonp requests. It can hardly be used. Give us the most useful information in XMLHTTPRequest: it lacks the request status information of XMLHTTPRequest, so it cannot trigger most callback functions, such as error, complete, etc. (jQuery1.9.0), and the success function that can be called back should presumably It is triggered by the load event of the script tag, which is completely different from the mechanism of ajax relying on the status of XMLHTTPRequest. After testing, it was found that zepto (v1.1.3), which was born out of jQuery, has an error in the jsonp request. For example, when the header returns a 401 error when loading a js document, the error function will be executed, but the jqXHR parameter of this function is also not an authentic jqXHR type. , we can't even get the response header information through it. In this case, we are just told that something went wrong in a certain link, but we don't know the specific error information. Similar to the scenario where the response header carries useful information, bloggers do not recommend using jsonp. It can be said that a prerequisite for using jsonp is: in addition to non-business exceptions such as network abnormalities, all business exceptions (in summary, are requests received from the server) All exceptions thrown during the return response period) need to be returned directly to the client in the form of request results to facilitate client callback analysis.

Thanks for reading, I hope it can help everyone, thank you for your support of this site!


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