AJAX cross-domain request workaround: Use JSONP to get JSON data

Source: Internet
Author: User
Tags domain server

Ajax does not allow cross-domain communication due to browser restrictions. If you try to request data from a different domain, a security error occurs. These security errors can be avoided if you have control over the remote server where the data resides and each request goes to the same domain. But what is the use of WEB applications if you only stay on your own servers? What if you need to collect data from multiple third-party servers?

Understanding the same-origin policy limitations

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

A relatively simple way to overcome this limitation is to have the Web page request data to the Web server it originates from, and have the Web server forward requests to a true third-party server like a proxy. Although the technology has been widely used, it is not scalable. Another way is to use frame features to create new zones in the current Web page, and get any third-party resources using GET requests. However, when resources are obtained, the content in the framework is limited by the same-origin policy.

The best way to overcome this limitation is to insert a dynamic script element into a Web page that points to a service URL in another domain and gets the data in its own script. It starts executing when the script loads. This approach is possible because the same-origin policy does not prevent dynamic script insertions and considers the script to be loaded from the domain that provides the Web page. However, if the script tries to load a document from another domain, it will not succeed. Fortunately, this technique can be improved by adding JavaScript Object Notation (JSON).

What is JSONP?

To understand JSONP, you have to mention JSON, so what is JSON?

JSONP (JSON with Padding) is an unofficial protocol that allows the server-side integration of script tags back to the client to achieve cross-domain access in the form of JavaScript callback (this is simply a JSONP implementation form).

What's the use of JSONP?

Due to the limitations of the same-origin policy, XMLHttpRequest only allows resources to request the current source (domain name, protocol, port), in order to implement cross-domain requests, cross-domain requests can be implemented through the script tag, and then output JSON data on the server and execute callback functions to resolve cross-domain data requests.

How do I use JSONP?

The demo below is actually a simple representation of JSONP, after the client declares the callback function, the client requests data across the domain through the script tag, then the server returns the corresponding data and executes the callback function dynamically.

1. HTML code (any one):

<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]);//Loop Output 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

<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]);//Loop Output a:1,b:2,etc.          }      }  </script>  <script type= "Text/javascript" src= "http://crossdomain.com/services.php?callback= Jsonpcallback ">    </script>  

JavaScript links must be under function.

2, Server PHP code

<?php  //server returns JSON data  $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) ";  Dynamic execution callback function  $callback =$_get[' callback '];  echo $callback. " ($result) ";  

3. jquery implementation

How to implement the client JS code in jquery 1:

<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]);//Loop Output a:1,b:2,etc.          }      });  </script>  

How to implement the client JS code in jquery 2:

<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]);//Loop Output A:1,b:2, etc.              }          },          timeout:3000      });  </script>  

How to implement the client JS code in jquery 3:

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

Where Jsoncallback is a function that is registered by the client and gets the JSON data on the cross-domain server after the callback.

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

This URL is a cross-domain server to take JSON data interface, the parameter is the name of the callback function, the return format is

Jsonpcallback ({msg: ' This is JSON data '})  
Jsonp principle:

First register a callback with the client and then pass the callback name to the server.

At this point, the server becomes JSON data.

Then, in JavaScript syntax, a function is generated, and the function name is the parameter Jsonp passed up.

Finally, the JSON data is placed directly into the function in the form of a parameter, so that a document of JS syntax is generated and returned to the client.

The client browser parses the script tag and executes the returned JavaScript document, where the data is passed in as a parameter to the client's pre-defined callback function. (Dynamic execution callback function)

The advantage of using JSON is that:

    • It's a lot lighter than XML, and it's not that much redundant stuff.
    • JSON is also very readable, but usually the return is compressed. Unlike a browser like XML can be directly displayed, the browser for the format of JSON display will need to use some plug-ins.
    • Working with JSON in JavaScript is simple.
    • Other languages such as PHP support for JSON is also good.

JSON also has some disadvantages:

    • JSON support in the service-side language is not as extensive as XML, but it json.org a library of many languages.
    • If you use eval () to parse, you are prone to security issues.

However, the advantages of JSON are obvious. is an ideal data format for AJAX data interaction.

Main tips:

JSONP is a powerful technology for building mashups, but unfortunately it is not a panacea for all cross-domain communication needs. It has some drawbacks that must be carefully considered before submitting development resources.

First, and most important, there is no error handling on the JSONP call. If the dynamic script insert is valid, the call is executed, and if it is not valid, the silence fails. There is no hint of failure. For example, you cannot catch a 404 error from the server, and you cannot cancel or restart the request. However, waiting for a period of time has not responded, do not have to ignore it. (The future JQuery version may have the feature to terminate the JSONP request.)

Another major drawback of JSONP is the danger of being used by untrusted services. Because the JSONP service returns a JSON response packaged in a function call, the function call is executed by the browser, which makes the host WEB application more susceptible to various types of attacks. If you intend to use the JSONP service, it is important to understand the threats it can pose.

AJAX cross-domain request workaround: Use JSONP to get JSON data

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.