Home Web Front-end JS Tutorial In-depth analysis of the principles of JSONP cross-domain_Basic knowledge

In-depth analysis of the principles of JSONP cross-domain_Basic knowledge

May 16, 2016 pm 04:27 PM
jsonp Cross domain

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, the JavaScript code contained in the page under baidu.com cannot access the content of the page 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" appears to be 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. JSONP works as described below: </p> <p>Suppose a GET request is submitted to <a href="http://example1.com/index.php">http://example2.com</a>/getinfo.php in the page <a href="http://example2.com">http://example1.com/index.php</a>, we can The following JavaScript code is placed in the page <a href="http://example1.com/index.php">http://example1.com/index.php</a> to implement: </p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="12864" class="copybut" id="copybut12864" onclick="doCopy('code12864')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code12864"> <br> var eleScript= document.createElement("script");<br> eleScript.type = "text/javascript";<br> eleScript.src = "<a href="http://example2.com/getinfo.php">http://example2.com/getinfo.php</a>";<br> document.getElementsByTagName("HEAD")[0].appendChild(eleScript);<br> </div> <p>When the GET request returns from <a href="http://example2.com/getinfo.php">http://example2.com/getinfo.php</a>, a piece of JavaScript code can be returned. This code will be automatically executed and can be used to call <a href="http://example1.com/index.php">http: //example1.com/index.php</a>A callback function in the page. </p> <p><strong>The advantage of JSONP is </strong>: 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. XMLHttpRequest or ActiveX support is required; and after the request is completed, the result can be returned by calling callback. </p> <p><strong>The disadvantage of JSONP is </strong>: 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 of two pages in different domains. How to make JavaScript calls between. </p> <p>Another example: </p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="4578" class="copybut" id="copybut4578" onclick="doCopy('code4578')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code4578"> <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) {//The callback function predefined by jquery on the client side. After successfully obtaining the json data on the cross-domain server, this callback function will be dynamically executed <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> </div> <p><strong>Sometimes you will see it written like this: </strong></p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="82552" class="copybut" id="copybut82552" onclick="doCopy('code82552')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code82552"> <br> $.getJSON("http://cross-domain dns/document!searchJSONResult.action?name1=" value1 "&jsoncallback=?", <br> Function(json){ <br> If(json.Attribute name==value){ <br> // Execute code <br> } <br> }); <br> </div> <p>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 not visible. </p> <p>In this way, jquery will be assembled into the following url get request: </p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="22073" class="copybut" id="copybut22073" onclick="doCopy('code22073')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code22073"> <br> http://cross-domain dns/document!searchJSONResult.action?&jsoncallback=jsonp1236827957501&_=1236828192549&searchWord=<br> Use case&currentUserId=5351&conditionBean.pageSize=15<br> </div> <p>On the response side (http://cross-domain dns/document!searchJSONResult.action), use jsoncallback = request.getParameter("jsoncallback") to get the js function name to be called back later on the jquery side: jsonp1236827957501 and then the content of the response For 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. </p> <p><strong>JSONP Principle</strong></p> <p>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. </p> <p>In this way, "jQuery AJAX cross-domain problem" has become a false proposition. The jquery $.ajax method name is misleading. </p> <p>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. </p> <p>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. </p> <p>jsonCallback function jsonp1236827957501(....): It is registered by the browser client. After obtaining the json data on the cross-domain server, the callback function </p> <p>The execution process of Jsonp is as follows: </p> <p>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 gets 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. </p> <p>Then use javascript syntax to generate a function. The function name is the value of the passed parameter 'jsoncallback' jsonp1236827957501.</p> <p>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. </p> <p>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 the jquery $.ajax() method in the above example) Encapsulated success: function (json)). </p> <p>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.

Thenwhy 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 be an optional solution for cross-domain data exchange in the future.

Let’s take a super simple example:

Copy code The code is as follows:

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
http://www.w3.org/1999/xhtml" >

Test Jsonp

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Solution to PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

How to make cross-domain requests in Vue? How to make cross-domain requests in Vue? Jun 10, 2023 pm 10:30 PM

Vue is a popular JavaScript framework for building modern web applications. When developing applications using Vue, you often need to interact with different APIs, which are often located on different servers. Due to cross-domain security policy restrictions, when a Vue application is running on one domain name, it cannot communicate directly with the API on another domain name. This article will introduce several methods for making cross-domain requests in Vue. 1. Use a proxy A common cross-domain solution is to use a proxy

How to use Flask-CORS to achieve cross-domain resource sharing How to use Flask-CORS to achieve cross-domain resource sharing Aug 02, 2023 pm 02:03 PM

How to use Flask-CORS to achieve cross-domain resource sharing Introduction: In network application development, cross-domain resource sharing (CrossOriginResourceSharing, referred to as CORS) is a mechanism that allows the server to share resources with specified sources or domain names. Using CORS, we can flexibly control data transmission between different domains and achieve safe and reliable cross-domain access. In this article, we will introduce how to use the Flask-CORS extension library to implement CORS functionality.

How to allow cross-domain use of images and canvas in HTML? How to allow cross-domain use of images and canvas in HTML? Aug 30, 2023 pm 04:25 PM

To allow images and canvases to be used across domains, the server must include the appropriate CORS (Cross-Origin Resource Sharing) headers in its HTTP response. These headers can be set to allow specific sources or methods, or to allow any source to access the resource. HTMLCanvasAnHTML5CanvasisarectangularareaonawebpagethatiscontrolledbyJavaScriptcode.Anythingcanbedrawnonthecanvas,includingimages,shapes,text,andanimations.Thecanvasisagre

How to use JSONP to implement cross-domain requests in Vue How to use JSONP to implement cross-domain requests in Vue Oct 15, 2023 pm 03:52 PM

Introduction to how to use JSONP to implement cross-domain requests in Vue. Due to the restrictions of the same-origin policy, the front-end will be hindered to a certain extent when making cross-domain requests. JSONP (JSONwithPadding) is a cross-domain request method. It uses the characteristics of the &lt;script&gt; tag to implement cross-domain requests by dynamically creating the &lt;script&gt; tag, and passes the response data back as a parameter of the callback function. This article will introduce in detail how to use JSONP in Vue

Cross-domain problems encountered in Vue technology development and their solutions Cross-domain problems encountered in Vue technology development and their solutions Oct 08, 2023 pm 09:36 PM

Cross-domain problems and solutions encountered in the development of Vue technology Summary: This article will introduce the cross-domain problems and solutions that may be encountered during the development of Vue technology. We'll start with what causes cross-origin, then cover a few common solutions and provide specific code examples. 1. Causes of cross-domain problems In web development, due to the browser's security policy, the browser will restrict requests from one source (domain, protocol or port) for resources from another source. This is the so-called "same origin policy". When we are developing Vue technology, the front-end and

Use CORS in Beego framework to solve cross-domain problems Use CORS in Beego framework to solve cross-domain problems Jun 04, 2023 pm 07:40 PM

With the development of web applications and the globalization of the Internet, more and more applications need to make cross-domain requests. Cross-domain requests are a common problem for front-end developers, and it can cause applications to not work properly. In this case, one of the best ways to solve the problem of cross-origin requests is to use CORS. In this article, we will focus on how to use CORS in the Beego framework to solve cross-domain problems. What is a cross-domain request? In web applications, cross-domain requests refer to requests from a web page of one domain name to another

Analyze PHP Session cross-domain error log processing Analyze PHP Session cross-domain error log processing Oct 12, 2023 pm 01:42 PM

PHPSession cross-domain error log processing When developing web applications, we often use PHP's Session function to track the user's status. However, in some cases, cross-domain errors may occur, resulting in the inability to access and operate Session data correctly. This article will introduce how to handle PHPSession cross-domain errors and provide specific code examples. What is PHPSession cross-domain error? Cross-domain error refers to the error in the browser

See all articles