Home Web Front-end JS Tutorial Detailed introduction to Javascript cross-domain knowledge

Detailed introduction to Javascript cross-domain knowledge

Nov 05, 2016 pm 04:37 PM
javascript

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>
Copy after login

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) { }
  //……
});
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles