AJAX cross-domain request-JSONP get JSON data

Source: Internet
Author: User
Tags script tag vars domain server

Asynchronous JavaScript and XML (Ajax ) are key technologies that drive a new generation of Web sites (popular terminology for Web 2.0 sites). Ajax allows data retrieval in the background without disturbing the display and behavior of the WEB application. Using XMLHttpRequest functions to get data, it is an API that allows client-side JavaScript to connect to a remote server via HTTP. Ajax is also a driving force for many mashups, which can make content collections from multiple locations a single WEB application.

However, because of browser restrictions, this method does not allow cross-domain communication. 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 a new zone in the current Web page, and use the GET request to get any third-party resources. 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).

1. What is JSONP?

To understand JSONP, you have to mention JSON, so 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-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).

2. What is 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.

3, how to 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.

HTML code (either ):

HTML code 
  1. <Meta content="text/html; Charset=utf-8 " http-equiv="content-type " />
  2. <script type="Text/javascript">
  3. function Jsonpcallback (Result) {
  4. alert (result);
  5. for (var i in result) {
  6. Alert (i+ ":" +result[i]);//loop output a:1,b:2,etc.
  7. }
  8. }
  9. var jsonp=document.createelement ("script");
  10. jsonp.type="Text/javascript";
  11. jsonp.src="Http://crossdomain.com/services.php?callback=jsonpCallback";
  12. document.getElementsByTagName ("Head") [0].appendchild (JSONP);
  13. </Script>

Or

HTML code 
  1. <Meta content="text/html; Charset=utf-8 " http-equiv="content-type " />
  2. <script type="Text/javascript">
  3. function Jsonpcallback (Result) {
  4. alert (RESULT.A);
  5. alert (result.b);
  6. alert (RESULT.C);
  7. for (var i in result) {
  8. Alert (i+ ":" +result[i]);//loop output a:1,b:2,etc.
  9. }
  10. }
  11. </Script>
  12. <script type="Text/javascript" src= "http://crossdomain.com/services.php?callback= Jsonpcallback "></script>

JavaScript links must be under function.

Server PHP Code (services.php):

PHP code 
  1. <?php
  2. The service side returns JSON data
  3. $arr =Array (' A ' =>1,' B ' =>2,' C ' =>3,' d ' =>4,' e ' =>5);
  4. $result =json_encode ($arr);
  5. Echo $_get[' callback ']. ' ("hello,world!") ';
  6. Echo $_get[' callback ']. " ($result) ";
  7. Dynamic Execution callback function
  8. $callback =$_get[' callback ');
  9. Echo $callback."  ($result) ";

If the above JS client code is implemented in jquery, it is also very simple.

$.getjson $.ajax $.get

How to implement the client JS code in jquery 1:

JS Code 
  1. <script type="Text/javascript" src="jquery.js" ></script>
  2. <script type="Text/javascript" >
  3. $.getjson ("http://crossdomain.com/services.php?callback=?",
  4. function (Result) {
  5. For (var i in result) {
  6. Alert (i+":" +result[i]);   Loop output a:1,b:2,etc.
  7. }
  8. });
  9. </script>

How to implement the client JS code in jquery 2:

JS Code 
  1. <script type="Text/javascript" src="jquery.js" ></script>
  2. <script type="Text/javascript" >
  3. $.ajax ({
  4. URL:"http://crossdomain.com/services.php",
  5. DataType:' Jsonp ',
  6. Data:",
  7. JSONP:' callback ',
  8. Success:function (Result) {
  9. For (var i in result) {
  10. Alert (i+":" +result[i]);   Loop output a:1,b:2,etc.
  11. }
  12. },
  13. timeout:3000
  14. });
  15. </script>

How to implement the client JS code in jquery 3:

JS Code 
    1. <script type="Text/javascript" src="jquery.js" ></script>
    2. <script type="Text/javascript" >
    3. $.get (' http://crossdomain.com/services.php?callback=? ', {name:encodeuricomponent (' tester ')},   function (JSON) { for (var i in JSON) alert (i+":" +json[i]);}, ' Jsonp ');
    4. </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 interface that takes JSON data, and the parameter is the name of the callback function, and the format returned is

JS Code 
    1. 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. He is an ideal data format for AJAX data interactions.

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.

Original address: http://justcoding.iteye.com/blog/1366102/

AJAX cross-domain request-JSONP 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.