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: 'http://crossdomain.com/jsonServerResponse', type: 'GET', dataType: 'jsonp', jsonp: "callback", jsonpCallback: 'functionName', 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!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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.

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
