search
HomeWeb Front-endJS TutorialDetailed introduction to Javascript cross-domain knowledge

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
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools