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

Detailed introduction to Javascript cross-domain knowledge

高洛峰
高洛峰Original
2016-12-08 13:58:351341browse

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 to dynamically add a 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag, and the src attribute of the script tag has no cross-domain restrictions. In this way, this cross-domain method has nothing to do with the ajax XmlHttpRequest protocol.

JSONP is JSON with Padding. Due to the restrictions of the same origin policy, XmlHttpRequest is only allowed to request resources from the current source (domain name, protocol, port). If we want to make a cross-domain request, we can make a cross-domain request by using the HTML script tag and return the script code to be executed in the response. This cross-domain communication method is called JSONP.

Let’s take a simple example:

<!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 callback name to the server (here the client and the server agree to query with the key as jsonp string value passed). 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)

jQuery’s Jsonp

As mentioned above, jsonp is not an ajax request, but jQuery still provides a way to make cross-domain requests consistent with jQuery.ajax:

$.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 Set to jsonp to indicate that 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, then jQuery will automatically generate a random function name ( Load a global function in the window object. 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 the ajax request, it is the authentic jqXHR object, which can also be regarded as the XMLHTTPRequest object (inherited or encapsulated), but this is not the case in the jsonp request. It can hardly bring Let’s take 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 is speculated to be Triggered by the load event of the script tag, this 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.


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