ajax学习笔记(二)
jsonp 跨域
什么是跨域?
答:根本原因是浏览器的同源策略,一个页面的ajax只能获取这个页面同源或者同域的数据,什么是同源或者同域呢,就是协议,域名,端口号都必须相同
http://localhost:3000 和 https://localhost:3000 //协议不同
http://localhost:3000 和 http:localhost:8080 //端口不同
http://www.baidu.com 和 http://www.google.com //域名不同
如何跨域请求?
解决办法 jsonp
jsonp 原理:利用script标签的跨域请求特性,通过src属性向服务器请求javascript文件,这和script标签引用外部文件一个原理
jsonp请求过程:
- 浏览器创建一个script标签,并给src赋值
- 发送请求
- 服务器数据相应,返回数据作为参数和函数名拼接在一起,浏览器接收到响应数据,相当于调用了回掉函数并且传入了一个参数 (如果这里看不明白,直接看例子结合这里的过程)
举个简单的例子
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button>请求jsonp内容</button>
<div></div>
<script>
var btn = document.querySelector('button')
var mydiv = document.querySelector('div')
var head = document.querySelector('head')
btn.onclick = function() {
//创建一个script标签
var script = document.createElement('script')
//设置script标签请求的地址,并传递参数回掉函数
script.src = 'http://localhost/jsonp/json.php?callback=test'
//添加节点到头部
head.appendChild(script)
}
//回掉函数
function test(str) {
mydiv.innerHTML = '我的名字叫'+str.name+'今年'+str.age+'岁'
}
</script>
</body>
</html>
json.php
<?php
$str = '{"name":"xiaoming","age":12,"love":"fangun"}';
$callback = $_GET['callback'];
// 执行回掉函数
echo $callback.'('.$str.')';
?>
兄弟连前端