JSONP是什么?
在介绍 JSONP 之前,先来介绍一下浏览器的同源策略。
同源策略
同源策略是由 Netscape(网景)提出的一个著名的安全策略,所有支持 JavaScript 的浏览器都支持这个策略。所谓同源是指域名、协议、端口都相同。以 http://c.biancheng网站站点" rel="nofollow" />
{"name":"C语言中文网", "url":"http://c.biancheng网站站点" rel="nofollow" /> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JavaScript</title> </head> <body> <div id="result"></div> <button type="button" onclick="sendAjax()">发送请求</button> <script> function sendAjax() { // 创建 XMLHttpRequest 对象 var request = new XMLHttpRequest(); // 实例化请求对象 request.open("GET", "http://localhost:8081/test.php"); // readyState 的变化 request.onreadystatechange = function() { // 检查请求是否成功 if(this.readyState === 4 && this.status === 200) { // 将来自服务器的响应插入当前页面 document.getElementById("result").innerHTML = this.responseText; } }; // 将请求发送到服务器 request.send(); } </script> </body> </html> Access to XMLHttpRequest at 'http://localhost:8081/test.php' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET http://localhost:8081/test.php net::ERR_FAILED
使用
<script>
标签,将标签的 src 属性设置为要请求的地址,如下所示:<script src="http://localhost:8081/test.php"></script>
这时您会发现,<script>
标签会自动解析并执行返回的内容,如果这些内容不是完整的 JavaScript 代码,程序就会报错,所有在进行 JSONP 跨域请求时,需要保证服务器返回一段完整的 JavaScript 代码。另外,返回的内容也不能是一段纯 JSON 的数据,因为 JSON 数据会自动转换为一个 JavaScript 对象,但不将其分配给变量或者传递给函数,我们也无法拿来使用。
因此,我们可以在请求中提供一个回调函数(被作为参数传递的函数,等同于一般函数),然后通过服务器返回这个函数,并将要返回的 JSON 数据作为函数的参数一同返回,这样
<script>
标签在解析并执行返回内容是就会自动调用这个函数。示例代码如下:<script src="http://localhost:8081/test.php?callback=showJsonData"></script>
服务器 http://localhost:8081/ 的完整代码如下所示:运行结果如下:<?php
$data = array('name'=>'C语言中文网', 'url'=>'http://c.biancheng网站站点" rel="nofollow" />
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
<script>
function showJsonData(data){
console.log(data);
}
</script>
<script src="http://localhost:8081/test.php?callback=showJsonData"></script>
</body>
</html>
{name: 'C语言中文网', url: 'http://c.biancheng网站站点" rel="nofollow" /> 注意:服务器返回的内容,必须是一段可执行的 JavaScript 代码,不能是其它内容。