English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Introduction to Cross-Domain Knowledge in Javascript

Summary of JS cross-domain knowledge:

Before the word 'cross-domain' appeared frequently, we had actually been using it frequently. For example, the img src of website A points to an image address on website B, without a doubt, this can be displayed normally in most cases (not to mention the anti-theft link technology); Similarly, the src attribute of the script tag can be set to point to script resources on other websites (in some cases, it is even encouraged to do so to make full use of the load advantages of other websites, reducing the concurrency of the server itself). However, if js is used to actively request data from other websites, such as the ajax method, it will encounter the annoying cross-domain problem, which is what we usually call cross-domain. Due to security reasons, cross-domain access is prohibited by default by all major browsers. This involves the concept of the same-origin policy: the same-origin policy prevents scripts loaded from one domain from accessing or manipulating document properties of 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 browsers isolate content from different sources to prevent them from operating between them.

The specific security issues brought about by cross-domain are not deeply explored by the blogger, everyone can fill in the blanks themselves.

However, in many cases, especially in today's continuously developing Internet, we need to request front-end interfaces from different partners or data providers. Before the method of cross-domain access is standardized (the demand for client-side cross-domain access seems to have also triggered w3Pay attention to c, as mentioned in the documents, html5 The WebSocket standard supports cross-domain data exchange and should also be a future optional solution for cross-domain data exchange. What methods can bypass its restrictions? There are many (although they are all麻烦), the most commonly used being the so-called JSONP cross-domain.

The principle of JSONP

The most basic principle of JSONP is: dynamically add a <script> tag, and the src attribute of the script tag has no cross-domain restriction. In this way, this cross-domain method is actually unrelated to the AJAX XmlHttpRequest protocol.

JSONP stands for JSON with Padding. Due to the restriction of the same-origin policy, XmlHttpRequest is only allowed to request resources from the current origin (domain, protocol, port). If cross-domain requests need to be made, we can use the HTML script tag to make cross-domain requests and return the script code to be executed in the response. This method of cross-domain communication is called JSONP.

Here is 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>

A brief description of the principle and process: First, register a callback on the client side, and then pass the name of the callback to the server (here, the client and server agree to pass the name of the callback as the query string value of the key jsonp). At this point, the server generates json data. Then, in the form of JavaScript syntax, it generates a function, the name of which is the parameter passed in jsonp. Finally, the json data is directly placed as an argument in the function, thus generating a JavaScript document in JavaScript syntax and returning it to the client. The client browser parses the script tag and executes the returned JavaScript document, which is equivalent to executing the predefined callback function.

From the above brief description, it can be concluded that: in addition to returning function-formatted js code snippets, the server can naturally return all executable js code snippets that meet the specifications.

The disadvantages of JSONP are: it only supports GET requests and does not support other types of HTTP requests such as POST; it only supports cross-domain HTTP requests in this case, and cannot solve the problem of how JavaScript calls are made between two pages in different domains. (There is more below)

jQuery's Jsonp

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

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

As shown above, setting dataType to jsonp indicates that this is a cross-domain request. jsonp is set as the query string key of the predefined function name on the server side, and jsonpCallback is the name of the js function; if jsonpCallback is not set, jQuery will automatically generate a random function name (loading a global function in the window object, which will be 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, it is not known whether the success function will be called back, or whether jQuery will look for the predefined function, and if it cannot find it, an error will be reported? The blogger is lazy, and will try it later.) Of course, jQuery provides a simple version, $.getJSON, which will not be elaborated here.

It is necessary to pay attention to the jqXHR parameter in the success function, which is a genuine jqXHR object in AJAX requests, and can also be regarded as an XMLHTTPRequest object (inheriting or encapsulating), but it is not the case in JSONP requests. It almost cannot provide us with the most useful information as XMLHTTPRequest does: it lacks the request status information of XMLHTTPRequest, so it cannot trigger most of the callback functions, such as error, complete, etc. (jQuery1.9.0), while the success function that can be called back should be triggered by the load event of the script tag, which is completely different from the mechanism of ajax relying on the state of XMLHTTPRequest. Through experiments, zepto (v1.1.3In the event of an error in a jsonp request, such as when loading a js document, the header returns401When an error occurs, the error function will be executed, but the jqXHR parameter of the function is also not a genuine jqXHR type, and it cannot be used to obtain the response header information. In this case, we are only informed that something is wrong, but we do not know the specific error information. In scenarios where useful information is carried by response headers, the blogger does not recommend using jsonp. It can be said that one of the prerequisites for using jsonp is: all business exceptions (in general, all exceptions thrown from the server request to the response time) need to be returned directly to the client in the form of request results, which is convenient for the client to call back and analyze.

Thank you for reading and hope it can help everyone. Thank you for your support of this site!

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to notice#w3Please send an email to codebox.com (replace # with @ when sending an email) to report any violations, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.

You May Also Like