Solution to js cross-origin request 5

Source: Internet
Author: User

Solution to js cross-origin request 5
This article mainly introduces the solution to js cross-origin requests in step 5. For more information, see

 

 

The cross-origin request data solution provides the following solutions:

?

1

2

3

4

5

JSONP Method

Form POST method

Server proxy

Html5 XDomainRequest

Flash 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 the Src attribute have cross-domain capabilities, such as: <script> <iframe>

4. Therefore, if you want to access data through cross-origin on a pure web side (ActiveX control, server proxy, Websocket that belongs to HTML5 in the future), you can only use the following method: it is to try to put data into js text on the remote server for the client to call and further process.

5. JSON is a pure character data format and can be supported by js native.

6. The 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 ).

7. After the client successfully calls the json file, it will obtain the required data, and the rest will be processed as needed.

8 in order to facilitate the client to use data, 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.

Specific implementation:

Regardless of jQuery, extjs, or other frameworks that support jsonp, the work they do is the same. Next I will explain the implementation of jsonp on the client step by step:

1. We know that even the code in the Cross-origin js file (of course, that complies with the web script Security Policy) can be executed unconditionally on the web page.

The remote server remoteserver.com root directory contains the following remote. js file code:

Alert ('am a remote file ');

The following figure shows the jsonp.html Page code of the worker server localserver.com:

?

1

2

3

4

5

6

7

8

9

10

<! 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> </title>

<Script type = "text/javascript" src = "http://remoteserver.com/remote.js"> </script>

</Head>

<Body>

 

</Body>

</Html>

There is no doubt that a prompt form will pop up, showing that the cross-origin call is successful.

2. Now we define a function on the jsonp.html page, and then input data in remote. js for calling.

The jsonp.html Page code is as follows:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<! 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> </title>

<Script type = "text/javascript">

Var localHandler = function (data ){

Alert ('I am a local function and can be called by cross-origin remote. js files. The data that remote js brings is:' + data. result );

};

</Script>

<Script type = "text/javascript" src = "http://remoteserver.com/remote.js"> </script>

</Head>

<Body>

 

</Body>

</Html>

The code of the remote. js file is as follows:

LocalHandler ({"result": "data from remote js "});
View the result after running. A Prompt window is displayed, indicating that the local function is successfully called by the cross-origin remote js and that the data of the remote js is 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.

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.

View the code on the jsonp.html page:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<! 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> </title>

<Script type = "text/javascript">

// Callback function after obtaining the Flight Information Query Result

Var flightHandler = function (data ){

Alert ('the result of your query is: Fare '+ data. price +' yuan, '+ 'remaining pass' + data. tickets +. ');

};

// Provide the url address of 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 = coding 98 & callback = flightHandler ";

// Create a script tag and set its attributes

Var script = document. createElement ('script ');

Script. setAttribute ('src', url );

// Add the script tag to the head. The call starts.

Document. getElementsByTagName ('head') [0]. appendChild (script );

</Script>

</Head>

<Body>

 

</Body>

</Html>

The code changes a lot this time, instead of Directly Writing remote js files to death, but coding for dynamic query, which is also the core part of jsonp client implementation, the focus of this example is how to complete the entire jsonp call process.

We can see that a code parameter is passed in the called url, telling the server that I want to check information about the 98 flights, while the callback parameter tells the server that my local callback function is called flightHandler, therefore, pass the query results to this function for calling.

?

1

2

3

4

5

FlightHandler ({

"Code": "000098 ",

"Price": 1780,

"Tickets": 5

});

We can see that what is passed to the flightHandler function is a json that describes the basic information of the flight. Run the page. A Prompt window is displayed. The jsonp execution process is successfully completed!

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.

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

OK ,the server is very intelligent. This code is generated on the page of flightresult.aspxand sent to jsonp.html (the implementation of the server is not demonstrated here. It has nothing to do with the language you choose. In the end, it is a concatenation string ):

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

<! 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> Untitled Page </title>

<Script type = "text/javascript" src = jquery. min. js "> </script>

<Script type = "text/javascript">

JQuery (document). ready (function (){

$. Ajax ({

Type: "get ",

Async: false,

Url: "http://flightQuery.com/jsonp/flightResult.aspx? Code = 98 ",

DataType: "jsonp ",

Jsonp: "callback", // The parameter name that is passed to the request handler or page to obtain the jsonp callback function name (generally: callback by default)

JsonpCallback: "flightHandler", // custom jsonp callback function name. The default value is the random function name automatically generated by jQuery. You can also write it "? ", JQuery will automatically process the data for you

Success: function (json ){

Alert ('You found the flight information: Fare: '+ json. price +' yuan, remaining ticket: '+ json. tickets +. ');

},

Error: function (){

Alert ('fail ');

}

});

});

</Script>

</Head>

<Body>

</Body>

</Html>

Isn't 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?

The above is all the content of this article. I hope you will like it.

 

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.