Home > Web Front-end > JS Tutorial > body text

AJAX cross-domain request JSONP to obtain JSON data

亚连
Release: 2018-05-24 17:25:03
Original
1814 people have browsed it

JSONP (JSON with Padding) is an unofficial protocol that allows integrating Script tags on the server side and returning them to the client, enabling cross-domain access in the form of javascript callback (this is just a simple implementation of JSONP).

Asynchronous JavaScript and XML (Ajax) is a key technology driving a new generation of Web sites (popularly known as Web 2.0 sites). Ajax allows data retrieval in the background without interfering with the display and behavior of the Web application. Get data using the XMLHttpRequest function, an API that allows client-side JavaScript to connect to a remote server over HTTP. Ajax is also the driving force behind many mashups, which integrate content from multiple places into a single Web application.

However, due to browser restrictions, this method does not allow cross-domain communication. If you try to request data from a different domain, a security error will occur. These security errors can be avoided if you can control the remote server where the data resides and if every request goes to the same domain. But what good is a web application if it just stays on its own server? What if you need to collect data from multiple third-party servers?

Understanding Same Origin Policy Restrictions

The Same Origin Policy prevents scripts loaded on one domain from obtaining 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 old and has existed 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 have the web server act like a proxy and forward the request to the actual third-party server. Although this technology has gained widespread use, it is not scalable. Another way is to use frame elements to create a new area within the current web page and use GET requests to obtain any third-party resources. However, after obtaining the resources, the content in the frame will be restricted by the same-origin policy.

A more ideal way to overcome this limitation is to insert a dynamic script element into a Web page whose source points to a service URL in another domain and fetches the data in its own script. It starts executing when the script loads. This approach works because the Same Origin Policy does not prevent dynamic script insertion and the script is treated as if it were loaded from the domain that serves the Web page. But if the script tries to load the document from another domain, it won't succeed. Fortunately, this technique can be improved upon by adding JavaScript Object Notation (JSON).

1. What is JSONP?

To understand JSONP, we 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 integrating Script tags on the server side and returning them to the client, enabling cross-domain access in the form of javascript callback (this is just a simple implementation of JSONP).

2. What is the use of JSONP?

Due to the restriction of the same-origin policy, XmlHttpRequest only allows requests for resources from 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 in the service The end outputs JSON data and executes the callback function, thus solving 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 cross-domain data from the server through the script tag, and then the server returns the corresponding data and Dynamically execute callback functions.

HTML code (either):

<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]);//循环输出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>
Copy after login

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]);//循环输出a:1,b:2,etc. 
    } 
  } 
</script> 

<script type="text/javascript" src="http://crossdomain.com/services.php?callback=jsonpCallback"></script>
Copy after login

JavaScript The link must be below the function.

Server-side PHP code (services.php):

<?php 
//服务端返回JSON数据 
$arr=array(&#39;a&#39;=>1,&#39;b&#39;=>2,&#39;c&#39;=>3,&#39;d&#39;=>4,&#39;e&#39;=>5); 
$result=json_encode($arr); 
//echo $_GET[&#39;callback&#39;].&#39;("Hello,World!")&#39;; 
//echo $_GET[&#39;callback&#39;]."($result)"; 
//动态执行回调函数 
$callback=$_GET[&#39;callback&#39;]; 
echo $callback."($result)";
Copy after login

If the above JS client code is implemented using jQuery, it is also very simple.

$.getJSON
$.ajax
$.get

Implementation method of client JS code in jQuery 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 in result) { 
      alert(i+":"+result[i]);//循环输出a:1,b:2,etc. 
    } 
  }); 
</script>
Copy after login

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:&#39;jsonp&#39;, 
    data:&#39;&#39;, 
    jsonp:&#39;callback&#39;, 
    success:function(result) { 
      for(var i in result) { 
        alert(i+":"+result[i]);//循环输出a:1,b:2,etc. 
      } 
    }, 
    timeout:3000 
  }); 
</script>
Copy after login

Client JS code in jQuery Implementation method 3:

Js code

<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript"> 
  $.get(&#39;http://crossdomain.com/services.php?callback=?&#39;, {name: encodeURIComponent(&#39;tester&#39;)}, function (json) { for(var i in json) alert(i+":"+json[i]); }, &#39;jsonp&#39;); 
</script>
Copy after login

Among them, jsonCallback is registered by the client and is a callback function after obtaining the json data on the cross-domain server.
http://crossdomain.com/services.php?callback=jsonpCallback
This url is the interface for the cross-domain server to obtain json data. The parameter is the name of the callback function, and the returned format is

Js code

jsonpCallback({msg:&#39;this is json data&#39;})
Copy after login

Jsonp principle:

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

At this time, the server first generates json data.

Then use javascript syntax to generate a function. The function name is the passed parameter jsonp.

Finally, the json data is placed directly into the function as a parameter, thus generating a js syntax document and returning it to the client.

The client browser parses the script tag and executes the returned javascript document. At this time, the data is passed as a parameter to the callback function predefined by the client. (Dynamic execution of the callback function)

The advantage of using JSON is:

It is much lighter than XML and does not have so many redundant things.

JSON is also very readable, but is usually returned compressed. Unlike XML, which can be displayed directly by browsers, browsers need to use some plug-ins to format JSON.

Handling JSON in JavaScript is easy.

Other languages ​​such as PHP also have good support for JSON.

JSON also has some disadvantages:

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

If you use eval() to parse, security issues may easily arise.

Despite this, the advantages of JSON are still obvious. It is an ideal data format for Ajax data interaction.

Main Tip:

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

First, and most importantly, there is no error handling for JSONP calls. If the dynamic script insertion is valid, the call is executed; if it is invalid, it fails silently. There is no prompt for failure. For example, 404 errors cannot be caught from the server, and requests cannot be canceled or restarted. However, if there is no response after waiting for a while, ignore it. (Future versions of jQuery may have features to terminate JSONP requests).

Another major drawback of JSONP is that it can be dangerous when used by untrusted services. Because the JSONP service returns a JSON response wrapped in a function call that is executed by the browser, it makes the host web application more vulnerable to a variety of attacks. If you plan to use a JSONP service, it's important to understand the threats it can pose.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Realize mobile phone positioning based on h5 ajax

Use the H5 feature FormData to upload files without refreshing

A detailed explanation of the use of various AJAX methods

The above is the detailed content of AJAX cross-domain request JSONP to obtain JSON data. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!