Home Web Front-end JS Tutorial JSONP cross-domain principle analysis and implementation introduction_javascript skills

JSONP cross-domain principle analysis and implementation introduction_javascript skills

May 16, 2016 pm 04:54 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, 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></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="93108" class="copybut" id="copybut93108" onclick="doCopy('code93108')"><u>Copy the code </u></a></span> The code is as follows :</div> <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> </div> <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 </u></a></span> The code is as follows: </div> <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> </div> <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 </u></a></span> The code is as follows: </div> <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> </div> <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:

Copy the code The code is as follows:




Test Jsonp






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

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

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

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

PHP Session cross-domain and cross-platform compatibility processing PHP Session cross-domain and cross-platform compatibility processing Oct 12, 2023 am 09:46 AM

PHPSession's cross-domain and cross-platform compatibility processing With the development of web applications, more and more developers are facing cross-domain problems. Cross-domain refers to a web page under one domain name requesting resources under another domain name. This increases the difficulty of development to a certain extent, especially for applications involving session (Session) management. It is a tricky problem. question. This article will introduce how to handle cross-domain session management in PHP and provide some specific code examples. Session Management is We

See all articles