


JSONP cross-domain principle analysis and implementation introduction_javascript skills
JavaScript is a front-end dynamic scripting technology often used in web development. In JavaScript, there is a very important security restriction called "Same-Origin Policy". This policy places important restrictions on the page content that JavaScript code can access, that is, JavaScript can only access content in the same domain as the document that contains it.
JavaScript security strategy is particularly important when performing multi-iframe or multi-window programming, as well as Ajax programming. According to this policy, JavaScript code contained in pages under baidu.com cannot access page content under the google.com domain name; even pages between different subdomains cannot access each other through JavaScript code. The impact on Ajax is that Ajax requests implemented through XMLHttpRequest cannot submit requests to different domains. For example, pages under abc.example.com cannot submit Ajax requests to def.example.com, etc.
However, when doing some in-depth front-end programming, cross-domain operations are inevitably required. At this time, the "same origin policy" becomes too harsh. JSONP cross-domain GET request is a common solution. Let's take a look at how JSONP cross-domain is implemented and discuss the principle of JSONP cross-domain.
The method of submitting HTTP requests to different domains by creating <script> nodes in the page is called JSONP. This technology can solve the problem of submitting Ajax requests across domains. The working principle of JSONP is as follows: <br><br> Assuming that a GET request is submitted to http://example2.com/getinfo.php in the page http://example1.com/index.php, we can put the following The JavaScript code is placed in the page http://example1.com/index.php to implement: <BR><div class="codetitle"><span><a style="CURSOR: pointer" data="93108" class="copybut" id="copybut93108" onclick="doCopy('code93108')"><U>Copy the code The code is as follows :<div class="codebody" id="code93108"> <BR>var eleScript= document.createElement("script"); <BR>eleScript.type = "text/javascript"; <BR>eleScript.src = "http://example2.com /getinfo.php"; <BR>document.getElementsByTagName("HEAD")[0].appendChild(eleScript); <BR> <BR>When a GET request is made from http://example2.com/getinfo.php When returning, you can return a piece of JavaScript code, which will be automatically executed and can be used to call a callback function in the http://example1.com/index.php page. <br><br>The advantage of JSONP is that it is not restricted by the same-origin policy like the Ajax request implemented by the XMLHttpRequest object; it has better compatibility and can run in older browsers without the need for XMLHttpRequest or ActiveX support; and after the request is completed, the result can be returned by calling callback. <br><br>The disadvantages of JSONP are: it only supports GET requests but not other types of HTTP requests such as POST; it only supports cross-domain HTTP requests and cannot solve the problem between two pages in different domains. Issues making JavaScript calls. <BR>Another example: <BR><div class="codetitle"><span><a style="CURSOR: pointer" data="84822" class="copybut" id="copybut84822" onclick="doCopy('code84822')"><U>Copy code The code is as follows: <div class="codebody" id="code84822"> <BR>var qsData = {' searchWord':$("#searchWord").attr("value"),'currentUserId': <BR>$("#currentUserId").attr("value"),'conditionBean.pageSize':$("# pageSize").attr("value")}; <BR>$.ajax({ <BR>async:false, <BR>url: http://cross-domain dns/document!searchJSONResult.action, <BR> type: "GET", <BR>dataType: 'jsonp', <BR>jsonp: 'jsoncallback', <BR>data: qsData, <BR>timeout: 5000, <BR>beforeSend: function(){ <BR> //This method is not triggered in jsonp mode. The reason may be that if dataType is specified as jsonp, it is no longer an ajax event <BR>}, <BR>success: function (json) {//Client jquery is predefined callback function, after successfully obtaining the json data on the cross-domain server, this callback function will be executed dynamically <BR>if(json.actionErrors.length!=0){ <BR>alert(json.actionErrors); <BR>} <BR>genDynamicContent(qsData,type,json); <BR>}, <BR>complete: function(XMLHttpRequest, textStatus){ <BR>$.unblockUI({ fadeOut: 10 }); <BR>}, <BR> error: function(xhr){ <BR>//This method is not triggered in jsonp mode. The reason may be that if dataType is specified as jsonp, it is no longer an ajax event<BR>//Request error handling<BR>alert(" Request error (please check the relevance network status.)"); <BR>} <BR>}); <BR>Sometimes you will also see this writing: <BR>$.getJSON("http://cross-domain dns/document!searchJSONResult.action?name1=" value1 "&jsoncallback=?", <BR>function(json){ <BR>if(json.property name==value){ <BR>//Execute code<BR>} <BR>}); <BR> <BR>This method is actually an advanced encapsulation of the $.ajax({..}) api in the above example. Some of the underlying parameters of the $.ajax api are Encapsulated and invisible. <BR>In this way, jquery will be assembled into the following url get request: <BR><div class="codetitle"><span><a style="CURSOR: pointer" data="62796" class="copybut" id="copybut62796" onclick="doCopy('code62796')"><U>Copy code The code is as follows: <div class="codebody" id="code62796"> <BR>http://cross-domain dns/document!searchJSONResult.action?&jsoncallback=jsonp1236827957501&_=1236828192549&searchWord= <BR>Use case¤tUserId=5351&conditionBean.pageSize=15 <BR> <BR>In response end (http://cross-domain dns/document!searchJSONResult.action), through jsoncallback = request.getParameter("jsoncallback") to get the js function name to be called back later on the jquery end: jsonp1236827957501. Then the content of the response is a Script Tags: "jsonp1236827957501("json array generated according to request parameters")"; jquery will dynamically load and call this js tag through the callback method:jsonp1236827957501(json array); This achieves the purpose of cross-domain data exchange. <br><br>JSONP Principle <BR>The most basic principle of JSONP is to dynamically add a <script> 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. <BR>In this way, "jQuery AJAX cross-domain problem" has become a false proposition. The jquery $.ajax method name is misleading. <BR>If set to dataType: 'jsonp', this $.ajax method has nothing to do with ajax XmlHttpRequest, and will be replaced by the JSONP protocol. JSONP is an unofficial protocol that allows integrating Script tags on the server side and returning them to the client, enabling cross-domain access in the form of javascript callbacks. <br><br>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 script tag of html and return the script code to be executed in the response, where the javascript object can be passed directly using JSON. This cross-domain communication method is called JSONP. <br><br>jsonCallback function jsonp1236827957501(....): It is registered by the browser client. After obtaining the json data on the cross-domain server, the execution process of the callback function <br><br>Jsonp is as follows: <BR>First register a callback (such as: 'jsoncallback') on the client, and then pass the callback name (such as: jsonp1236827957501) to the server. Note: After the server obtains the callback value, it must use jsonp1236827957501(...) to include the json content to be output. At this time, the json data generated by the server can be correctly received by the client. <br><br>Then use javascript syntax to generate a function. The function name is the value jsonp1236827957501 of the passed parameter 'jsoncallback'. <BR>Finally, place the json data directly into the function as a parameter. This generates a js syntax document and returns it to the client. <br><br>The client browser parses the script tag and executes the returned javascript document. At this time, the javascript document data is passed as a parameter to the callback function predefined by the client (such as jquery $.ajax in the above example) () method encapsulated in success: function (json)). <BR>It can be said that the jsonp method is consistent in principle with <script src="http://cross-domain/...xx.js"></script> (qq space uses this method extensively to achieve cross-domain data exchange). JSONP is a script injection (Script Injection) behavior, so it has certain security risks.
Then why doesn’t jquery support cross-domain post?
Although using post to dynamically generate iframe can achieve the purpose of post cross-domain (this is how a js expert patched jquery1.2.5), this is a relatively extreme method and is not recommended.
It can also be said that the cross-domain method of get is legal, and the post method is considered illegal from a security perspective. It is best not to take the wrong approach as a last resort.
The demand for cross-domain access on the client side seems to have attracted the attention of w3c. According to the information, the html5 WebSocket standard supports cross-domain data exchange and should also be an optional solution for cross-domain data exchange in the future.
Let’s take a super simple example:
> ;
Among them, jsonCallback is the function registered by the client to call back after obtaining the json data on the cross-domain server. http://crossdomain.com/jsonServerResponse?jsonp=jsonpCallback This URL is the interface for cross-domain servers to obtain json data. The parameter is the name of the callback function. The returned format is: jsonpCallback({msg:'this is json data'})
Briefly describe the principle and process: first register a callback on the client, and then pass the callback name to the server. At this point, the server first generates json data. Then use javascript syntax to generate a function. 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. At this time, the data is passed as a parameter to the callback function predefined by the client. (Dynamic execution of callback function)

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 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.

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.

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.

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.

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

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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

WebStorm Mac version
Useful JavaScript development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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