Solution to js cross-origin request 5-javascript tips

Source: Internet
Author: User
Tags form post
This article mainly introduces the solution of js cross-origin request 5. For more information, see the following solutions for cross-origin request data:

JSONP form POST method server proxy Html5 XDomainRequestFlash request

Separate description:

I. JSONP:

Intuitive understanding:

Is to dynamically register a function on the client.

Function a (data), and then upload the function name to the server. the server returns a ({/* json */}) to the client for running.

Function a (data) to implement cross-origin.

Background:

1. there is a problem that Ajax requests common files directly without cross-origin access permissions. render manager does not support static pages, dynamic web pages, web services, and wcf requests as long as they are cross-origin requests.

2. However, this does not affect webpage calls to js files.

3. for further promotion, we found that all tags with Src attributes have cross-domain capabilities, such as script.&lt;/P&gt; &lt;p&gt; 4. Therefore, if you want to access data through cross-origin on a pure web side (ActiveX control, server proxy, Websocket of HTML5 in the future, etc, you can only use the following method: it is to try to load data into js text on the remote server for the client to call and further process. &lt;/P&gt; &lt;p&gt; 5. JSON is a pure character data format and supported by js native. &lt;/P&gt; &lt;p&gt; 6. this solution is released: the web client uses the same method as the call script, to call the js format files dynamically generated on the cross-origin server (generally with the suffix of json ). &lt;/P&gt; &lt;p&gt; 7. after the client successfully calls the json file, it obtains the required data. The rest is to process the data as needed. &lt;/P&gt; &lt;p&gt; 8 to facilitate client data use, an informal transmission protocol is gradually formed, called jsonp. One important aspect of this protocol is to allow users to pass a callback parameter to the server. when the server returns data, the callback parameter is used as the function name to enclose json data, in this way, the client can customize its own functions to process the returned data. &lt;/P&gt; &lt;p&gt; specific implementation: &lt;/p&gt; &lt;p&gt; no matter jQuery, extjs, or other frameworks that support jsonp, the work behind the scenes is the same. next I will explain the implementation of jsonp on the client step by step: &lt;/p&gt; &lt;p&gt; 1. we know that, even if the code in the cross-origin js file (of course, it complies with the web script security policy), the web page can be executed unconditionally. &lt;/P&gt; &lt;p&gt; The remote server remoteserver.com root directory contains a remote. the js file code is as follows: &lt;/p&gt; &lt;p&gt; alert ('My remote file'); &lt;/p&gt; &lt;p&gt; The jsonp.html page code of the worker server localserver.comis as follows: &lt;/p&gt; &lt;p class = "jb51code"&gt; &lt;pre class = "brush: js;"&gt; &lt;! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN "" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt; &lt;Html xmlns =" http://www.w3.org/1999/xhtml "&gt; &lt;Head&gt; &lt;title&gt; &lt;/title&gt; &lt;script type =" text/javascript "src =" http://remoteserver.com/remote.js?7.1.2 "&gt; Script </pead&gt; &lt;body&gt; </ptml&gt; &lt;/pre&gt; &lt;/p&gt; &lt;p&gt; no doubt, A prompt is displayed, indicating that the cross-origin call is successful. &lt;/P&gt; &lt;p&gt; 2. Now we define a function on the jsonp.html page, and then input data in remote. js for calling. &lt;/P&gt; &lt;p&gt; The jsonp.html page code is as follows: &lt;/p&gt; &lt;p class = "jb51code"&gt; &lt;pre class = "brush: js;"&gt; &lt;! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN "" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt; &lt;Html xmlns =" http://www.w3.org/1999/xhtml "&gt; &lt;Head&gt; &lt;title&gt; &lt;/title&gt; &lt;script type =" text/javascript "&gt; var localHandler = function (data) {alert ('I am a local function, cross-Origin remote. js file call. the remote js data is: '+ data. result) ;}; script &lt;script type = "text/javascript" src =" http://remoteserver.com/remote.js?7.1.2 "&gt; Script </pead&gt; &lt;body&gt; </ptml&gt; &lt;/pre&gt; &lt;/p&gt; &lt;p&gt; remote. the js file code is as follows: &lt;/p&gt; &lt;p&gt; localHandler ({"result": "data I am from remote js"}); &lt;br/&gt; view the result after running, A prompt window is displayed, showing that the local function is successfully called by cross-origin remote js, and the data of remote js is also received. I'm glad that the goal of cross-origin remote data retrieval is basically achieved, but another problem arises. how can I let remote js know the name of the local function that should be called? After all, jsonp service providers have to deal with many service objects, and these service objects have different local functions? Let's look down. &lt;/P&gt; &lt;p&gt; 3. smart developers can easily imagine that as long as the js scripts provided by the server are dynamically generated, in this way, the caller can pass a parameter and tell the server that "I want a js code to call the XXX function. please return it to me ", as a result, the server can generate js scripts and respond to the requirements of the client. &lt;/P&gt; &lt;p&gt; view the code on the jsonp.html page: &lt;/p&gt; &lt;p class = "jb51code"&gt; &lt;pre class = "brush: js;"&gt; &lt;! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN "" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt; &lt;Html xmlns =" http://www.w3.org/1999/xhtml "&gt; &lt;Head&gt; &lt;title&gt; &lt;/title&gt; &lt;script type =" text/javascript "&gt; // callback function var flightHandler = function (data) after the flight information query result is obtained) {alert ('your query result is: Fare '+ data. price + 'Yuan, '+ 'remaining votes' + data. tickets +. ') ;}; // Url that provides the jsonp service (no matter what type of address, the final returned value is a piece of javascript code) var url =" http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998 &amp; Callback = flightHandler "; // create a script tag and set its attribute var script = document. createElement ('script'); script. setAttribute ('src', url); // add the script tag to the head. at this time, the document is called. getElementsByTagName ('head') [0]. appendChild (script ); script </pead&gt; &lt;body&gt; </ptml&gt; &lt;/pre&gt; &lt;/p&gt; &lt;p&gt; The Code changes a lot this time, no longer directly writing remote js files to death, but encoding for dynamic query, which is also the core part of the jsonp client implementation. the focus in this example is how to complete the whole process of jsonp calls. &lt;/P&gt; &lt;p&gt; we can see that a code parameter is passed in the called url, telling the server what I want to query is the information of the 98 flights, while the callback parameter tells the server, my local callback function is called flightHandler, so please pass the query result into this function for calling. &lt;/P&gt; &lt;p class = "jb51code"&gt; &lt;pre class = "brush: js;"&gt; flightHandler ({"code": "000098", "price": 1780, "tickets": 5}); &lt;/pre&gt; &lt;/p&gt; &lt;p&gt; we can see that what is passed to the flightHandler function is a json that describes the basic flight information. Run the page. a prompt window is displayed. the jsonp execution process is successfully completed! &lt;/P&gt; &lt;p&gt; 4. so far, I believe you can understand the implementation principles of the jsonp client? The rest is how to encapsulate the code to facilitate interaction with the user interface, so as to implement multiple and repeated calls. &lt;/P&gt; &lt;p&gt; What? You are using jQuery. how does jQuery implement jsonp calling? Okay, let me look at it and give you another piece of code for jQuery to use jsonp (we still use the example of the flight information query above, assuming that the return result of jsonp remains unchanged ): &lt;/p&gt; &lt;p&gt; OK ,the server is very intelligent. the page calling flightresult.aspxgenerates the following code example to jsonp.html (the server implementation is not demonstrated here. it has nothing to do with the language you selected. In the end, it is a concatenation string ): &lt;/p&gt; &lt;p class = "jb51code"&gt; &lt;pre class = "brush: js;"&gt; &lt;! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN "" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "&gt; &lt;Html xmlns =" http://www.w3.org/1999/xhtml "&gt; &lt;Head&gt; &lt;title&gt; Untitled Page &lt;/title&gt; &lt;script type =" text/javascript "src = jquery. min. js? 7.1.2 "&gt; script &lt;script type =" text/javascript "&gt; jQuery (document ). ready (function () {$. ajax ({type: "get", async: false, url :" http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998 ", DataType:" jsonp ", jsonp:" callback ", // The parameter name that is passed to the request handler or page to obtain the jsonp callback function name (generally the default value is: callback) jsonpCallback: "flightHandler", // custom jsonp callback function name. The default value is the random function name automatically generated by jQuery. you can also enter "&amp; #63 ;", jQuery will automatically process the data for you. success: function (json) {alert ('your queried flight information: fare: '+ json. price + 'Yuan, remaining ticket: '+ json. tickets +. ') ;}, Error: function () {alert ('fail ');}});}); script </pead&gt; &lt;body&gt; </ptml&gt; &lt;/pre&gt; &lt;/p&gt; &lt;p&gt; Is it strange? Why didn't I write the flightHandler function this time? And the operation was successful! Haha, this is jQuery's credit. when jquery is dealing with jsonp-type ajax (it can't help but vomit, although jquery also classifies jsonp as ajax, but they are really not the same thing.) is it nice to automatically generate a callback function and extract the data for the success attribute method to call? &lt;/P&gt; &lt;p&gt; The above is all about this article. I hope you will like it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.