Ajax Cross domain request JSONP get JSON data _ajax related

Source: Internet
Author: User
Tags error handling script tag domain server

Asynchronous JavaScript and XML (Ajax) is a key technology that drives a new generation of Web sites (popular term for Web 2.0 sites). Ajax allows data retrieval in the background without interfering with the display and behavior of WEB applications. Using the XMLHttpRequest function to get data, it is an API that allows client JavaScript to connect to a remote server via HTTP. Ajax is also a driving force for many mashups, which can make content sets from multiple locations into a single WEB application.

However, this method does not allow Cross-domain communication due to browser restrictions. If you try to request data from a different domain, a security error occurs. You can avoid these security errors if you can control the remote server where the data resides and each request goes to the same domain. But what's the use of WEB applications if you just stay on your own server? What if you need to collect data from multiple Third-party servers?

Understanding homology policy restrictions

The homology policy prevents scripts loaded from one domain from acquiring or manipulating document properties on another domain. In other words, the domain of the requested URL must be the same as the current Web page's domain. This means that the browser isolates content from different sources to prevent action between them. This browser strategy is very old and has been around since Netscape Navigator version 2.0.

A relatively simple way to overcome this limitation is to have the Web page request data from the Web server it originated from, and to have the Web server forward the request to a real Third-party server like a proxy. Although the technology has been widely used, it is not scalable. Another way is to use the framework elements to create a new zone in the current Web page and use a GET request to obtain any third-party resources. However, when a resource is obtained, the content in the framework is limited by the homology policy.

An ideal 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 method is feasible because the homology 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?

The JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript and 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 script tags to be returned to the client and Cross-domain access through JavaScript callback (this is simply a JSONP form of implementation).

2. What is the use of JSONP?

Due to the restriction of the homology policy, XMLHttpRequest only allows resources to request the current source (domain name, protocol, port), and in order to implement Cross-domain requests, Cross-domain requests can be implemented through the script tag, and then the JSON data and the callback function are executed on the server, thus resolving 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 the data across the domain through the script tag, and then the server returns the corresponding data and executes the callback function dynamically.

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

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 on 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 below the function.

Service-side PHP code (services.php):

<?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 of callback functions 
$callback =$_get[' callback ']; 

If the above JS client code in the jquery method to achieve, but also very simple.

$.getjson
$.ajax
$.get

Client JS code in jquery implementation Mode 1:

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) { 
      alert (i+ ":" +result[i]);//Loop Output a:1,b:2,etc. 
    } 
  }); 

Client JS code in jquery implementation Mode 2:

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 by result) { 
        alert (i+: "+result[i]);/loop output a:1,b:2,etc. 
      } 
    }, 
    timeout:3000 
  }); 

Client JS code in jquery implementation Mode 3:

JS Code

<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 '); 

Where Jsoncallback is registered by the client, gets the function of the callback after the JSON data is on the Cross-domain server.
Http://crossdomain.com/services.php?callback=jsonpCallback
This URL is an interface for JSON data across a domain server, the name of the callback function, and the returned format

JS Code

 
  

Jsonp principle:

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

At this point, the server is being 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 into function directly in the form of a parameter, which generates a document of JS syntax and returns it to the client.

The client browser parses the script tag and executes the returned JavaScript document, where the data is passed as a parameter into the client's predefined callback function. (Dynamic execution of callback functions)

The advantage of using JSON is that:

Much lighter than XML, with less redundancy.

JSON is also good for readability, but usually the return is compressed. Unlike XML, browsers can directly show that the browser's formatted display of JSON needs some plug-ins.

Processing JSON in JavaScript is simple.

Other languages, such as PHP, are also good for JSON support.

JSON also has some disadvantages:

JSON's support for server-side languages is not as extensive as XML, but it provides libraries for many languages on json.org.

If you use eval () to parse it, security issues are likely to arise.

Nevertheless, 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 considered carefully before submitting development resources.

First, and most important, there is no error handling for JSONP calls. If the dynamic script insert is valid, the call is executed, and if it is invalid, the silence fails. There is no hint of failure. For example, you cannot catch 404 errors from the server, and you cannot cancel or restart the request. However, wait for some time has not responded, it is not to ignore it. (future jQuery versions may have attributes that terminate JSONP requests).

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

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.