AJAX cross-origin request for JSONP to obtain the JSON data instance code, jsonpjson

Source: Internet
Author: User

AJAX cross-origin request for JSONP to obtain the JSON data instance code, jsonpjson

Asynchronous Javascript and XML (Ajax) is a key technology driving the next generation of Web sites (commonly referred to as Web 2.0 sites. Ajax allows data retrieval in the background without interfering with the display and behavior of Web applications. The XMLHttpRequest function is used to obtain data. It is an API that allows the client Javascript to connect to a remote server over HTTP. Ajax is also the driving force of many MashUps, which can integrate content from multiple places into a single Web application.

However, due to browser restrictions, this method does not allow cross-origin communication. If you try to request data from different domains, a security error occurs. If you can control the remote server where data resides and each request is sent to the same domain, you can avoid these security errors. However, what is the use of Web applications if they only stay on their own servers? What should I do if I need to collect data from multiple third-party servers?

Understanding the same-origin policy

The same-origin policy prevents scripts loaded from one domain from obtaining or operating on document properties in another domain. That is to say, the domain of the requested URL must be the same as that of the current Web page. This means that the browser isolates content from different sources to prevent operations between them. This browser policy is old and has existed since Netscape Navigator 2.0.

A relatively simple way to overcome this limitation is to request data from a Web page to the Web server it originated from, and let the Web server forward the request to a real third-party server like a proxy. Although this technology is widely used, it cannot be scaled. Another method is to use the framework element to create a region in the current Web page and use the GET request to obtain any third-party resources. However, after obtaining resources, the content in the framework will be restricted by the same-source policy.

An ideal way to overcome this restriction is to insert a dynamic script element into the Web page. The page source points to the service URL in another domain and obtains data in its own script. When the script is loaded, it starts to execute. This method is feasible because the same-origin policy does not prevent dynamic script insertion and regards the script as being loaded from the domain that provides the Web page. However, if the script tries to load the document from another domain, it will not succeed. Fortunately, this technology can be improved by adding Javascript Object Notation (JSON.

1. What is JSONP?

To understand JSONP, I have to mention JSON. What is JSON?

JSON is a subset of the object literal notation of Javascript. Since JSON is a subset of Javascript, it can be used in the language with no muss or fuss.

JSONP (JSON with Padding) is an unofficial protocol that allows the server to integrate script tags to return to the client, cross-origin access is implemented through javascript callback (this is only a simple implementation form of JSONP ).

2. What is JSONP used?

Due to the restrictions of the same-origin policy, XmlHttpRequest only allows requests to resources of the Current Source (domain name, protocol, Port). To implement cross-origin requests, you can use the script tag to implement cross-origin requests, then, the server outputs JSON data and executes the callback function to resolve cross-Origin data requests.

3. How to Use JSONP?

The DEMO below is actually a simple form of JSONP. After the client declares the callback function, the client uses the script tag to request data from the server across domains, then the server returns the corresponding data and dynamically executes the callback function.

HTML code (any ):

<Meta content = "text/html; charset = UTF-8" http-equiv = "Content-Type"/> <script type = "text/javascript"> function jsonpCallback (result) {// alert (result); for (var I in result) {alert (I + ":" + result [I]); // cyclically Outputs a: 1, B: 2, etc .}} var JSONP = document. createElement ("script"); JSONP. type = "text/javascript"; JSONP. src = "http://crossdomain.com/services.php? Callback = jsonpCallback "; document. getElementsByTagName (" head ") [0]. appendChild (JSONP); </script>

Or

Html code

<Meta content = "text/html; charset = UTF-8" http-equiv = "Content-Type"/> <script type = "text/javascript"> function jsonpCallback (result) {alert (result. a); alert (result. b); alert (result. c); for (var I in result) {alert (I + ":" + result [I]); // cyclically Outputs a: 1, B: 2, etc .}} </script> <script type = "text/javascript" src = "http://crossdomain.com/services.php? Callback = jsonpCallback "> </script>

The Javascript link must be under the function.

Server PHP code (services. php ):

Php code

<? Php // JSON data returned by the server $ arr = array ('A' => 1, 'B' => 2, 'c' => 3, 'D' => 4, 'E' => 5); $ result = json_encode ($ arr); // echo $ _ GET ['callback']. '("Hello, World! ") '; // Echo $ _ GET ['callback']. "($ result)"; // The callback function $ callback =$ _ GET ['callback']; echo $ callback. "($ result )";

If you use jQuery to implement the above JS client code, it is also very simple.

$.getJSON$.ajax$.get

Implementation Method 1 of client JS Code in jQuery:

Js Code

<Script type = "text/javascript" src = "jquery. js"> </script> <script type = "text/javascript"> $. getJSON ("http://crossdomain.com/services.php? Callback =? ", Function (result) {for (var I in result) {alert (I +": "+ result [I]); // cyclically Outputs a: 1, B: 2, etc .}}); </script>

Implementation Method 2 of client JS Code in jQuery:

Js Code

<Script type = "text/javascript" src = "jquery. js "> </script> <script type =" text/javascript "> $. ajax ({url: "http://crossdomain.com/services.php", dataType: 'jsonp', data: '', jsonp: 'callback', success: function (result) {for (var I in result) {alert (I + ":" + result [I]); // cyclically Outputs a: 1, B: 2, etc .}}, timeout: 3000}); </script>

Implementation Method 3 of client JS Code in jQuery:

<Script type = "text/javascript" src = "jquery. js"> </script>
<Script type = "text/javascript">
$. Get ('HTTP: // crossdomain.com/services.php? Callback =? ', {Name: encodeURIComponent ('tester')}, function (json) {for (var I in json) alert (I + ": "+ json [I]) ;}, 'jsonp ');
</Script>
 
Among them, jsonCallback is registered by the client. After obtaining json data on the Cross-origin server, it calls back the function.

Http://crossdomain.com/services.php? Callback = jsonpCallback

This url is the interface for the cross-origin server to retrieve json data. The parameter is the name of the callback function and the returned format is

jsonpCallback({msg:'this is json data'})  

Jsonp principle:

Register a callback on the client, and then pass the callback name to the server.

In this case, the server is converted into json data.
Then, a function is generated in javascript syntax. The function name is the passed parameter jsonp.

Finally, place the json data directly in the function as an input parameter. In this way, a js syntax document is generated and returned to the client.

The client browser parses the script tag and executes the returned javascript document. As a parameter, the data is passed into the pre-defined callback function of the client. (The callback function is dynamically executed)

JSON has the following advantages:

It is much lighter than XML, and there is not so much redundancy.

JSON is also readable, but usually the returned results are compressed. Unlike browsers like XML, the browser can directly display JSON format. Some plug-ins are required for browser formatting.

Processing JSON in Javascript is simple.

Other languages such as PHP have good support for JSON.

JSON also has some disadvantages:

JSON is not widely supported as XML on the server side, but JSON.org provides libraries in many languages.

If you use eval () for parsing, security issues may occur.

However, the advantages of JSON are obvious. He is an ideal method for Ajax data interaction.

TIPS:

JSONP is a powerful technique for building mashup, but unfortunately it is not a panacea for all cross-domain communication needs. It has some defects and must be carefully considered before submitting development resources.

First, and most importantly, there is no error handling for JSONP calls. If the dynamic script insertion is valid, the call is executed. If the dynamic script insertion is invalid, the silent operation fails. There is no prompt for failure. For example, a 404 error cannot be captured from the server, or the request cannot be canceled or restarted. However, if you haven't responded for a while, you don't have to worry about it. (In future jQuery versions, the JSONP request may be terminated ).

Another major defect of JSONP is that it is dangerous to be used by untrusted services. Because the JSONP service returns the JSON response packaged in the function call, and the function call is executed by the browser, the host Web application is more vulnerable to various attacks. If you plan to use the JSONP service, it is very important to understand the threats it can cause.

The above is an example code of AJAX cross-origin request for JSONP to obtain JSON data. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.