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

AJAX cross-domain request JSONP detailed steps to obtain JSON data (with code)

php中世界最好的语言
Release: 2018-04-02 14:19:56
Original
3167 people have browsed it

This time I will bring you a detailed explanation of the steps for AJAX cross-domain request JSONP to obtain JSON data (with code), what are the precautions for AJAX cross-domain request JSONP to obtain JSON data, the following is a practical case, one Get up and take a look.

Asynchronous JavaScript and XML (Ajax) are key technologies driving the 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 mistakes 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 the Same Origin Policy

The Same Origin Policy prevents scripts loaded from 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 from which it originated, 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 callbacks (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 is only allowed to request 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. Then output JSON data on the server side and execute Callback function, thereby 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 data from the server across domains through the script tag, and then the server returns the corresponding data and dynamically executes the callback. function.

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

The JavaScript link must be below the function.

Server-side PHP code (services.php):

Php code

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

If the above JS client code It is also very simple to implement using jQuery.

$.getJSON
$.ajax
$.get
Copy after login

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

客户端JS代码在jQuery中的实现方式2:

Js代码 

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

客户端JS代码在jQuery中的实现方式3:

 
 
 
其中 jsonCallback 是客户端注册的,获取跨域服务器上的json数据后,回调的函数。

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

这个 url 是跨域服务器取 json 数据的接口,参数为回调函数的名字,返回的格式为

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

Jsonp原理:

首先在客户端注册一个callback, 然后把callback的名字传给服务器。

此时,服务器先生成 json 数据。
然后以 javascript 语法的方式,生成一个function , function 名字就是传递上来的参数 jsonp.

最后将 json 数据直接以入参的方式,放置到 function 中,这样就生成了一段 js 语法的文档,返回给客户端。

客户端浏览器,解析script标签,并执行返回的 javascript 文档,此时数据作为参数,传入到了客户端预先定义好的 callback 函数里.(动态执行回调函数)

使用JSON的优点在于:

比XML轻了很多,没有那么多冗余的东西。

JSON也是具有很好的可读性的,但是通常返回的都是压缩过后的。不像XML这样的浏览器可以直接显示,浏览器对于JSON的格式化的显示就需要借助一些插件了。

在JavaScript中处理JSON很简单。

其他语言例如PHP对于JSON的支持也不错。

JSON也有一些劣势:

JSON在服务端语言的支持不像XML那么广泛,不过JSON.org上提供很多语言的库。

如果你使用eval()来解析的话,会容易出现安全问题。

尽管如此,JSON的优点还是很明显的。他是Ajax数据交互的很理想的方式。

主要提示:

JSONP 是构建 mashup 的强大技术,但不幸的是,它并不是所有跨域通信需求的万灵药。它有一些缺陷,在提交开发资源之前必须认真考虑它们。

第一,也是最重要的一点,没有关于 JSONP 调用的错误处理。如果动态脚本插入有效,就执行调用;如果无效,就静默失败。失败是没有任何提示的。例如,不能从服务器捕捉到 404 错误,也不能取消或重新开始请求。不过,等待一段时间还没有响应的话,就不用理它了。(未来的 jQuery 版本可能有终止 JSONP 请求的特性)。

JSONP 的另一个主要缺陷是被不信任的服务使用时会很危险。因为 JSONP 服务返回打包在函数调用中的 JSON 响应,而函数调用是由浏览器执行的,这使宿主 Web 应用程序更容易受到各类攻击。如果打算使用 JSONP 服务,了解它能造成的威胁非常重要。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

使用Blod做出ajax的进度条下载

在实战项目中Ajax应该如何传递JSON

The above is the detailed content of AJAX cross-domain request JSONP detailed steps to obtain JSON data (with code). 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