批改状态:合格
老师批语:同源策略限制了脚本发起http请求, 但不限制标签属性的跨域请求...., 之前用iframe来解决, 现在可以用jsonp方式来处理, 借助ajax更高效的方式处理跨域
CORS是一个W3C标准,全称是“跨域资源共享”.它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
前台部分
<title>跨域请求</title></head><body><button>跨域请求</button><h2></h2></body><script>var btn = document.querySelector("button");btn.addEventListener("click",function () {// 创建AJAX对象var xhr = new XMLHttpRequest();// 监听请求xhr.onreadystatechange = function () {if (xhr.readyState === 4 && xhr.status === 200){console.log(xhr.responseText);document.querySelector("h2").innerHTML = xhr.responseText;}};// 初始化请求参数xhr.open("GET","http://m.xt520.xyz/cors.php",true);xhr.send(null);},false);</script>
后台部分:
<?phpheader('Access-Control-Allow-Origin:*');header('content-type:text/html;charset=utf-8');echo "这是服务器上的资源";flush();?>
效果图:
注意点:
1.Access-Control-Allow-Origin:表示允许任何域名跨域访问,如果需要指定域名才允许跨域访问,只需把Access-Control-Allow-Origin:允许的域名。
前台部分:
<body><button>跨域请求——JSONP</button><script>// 1.准备好处理回调函数function handle(jsonData) {console.log(jsonData);var data = JSON.parse(jsonData);console.log(data);// 将接口返回的数据渲染到页面中var ul = document.createElement("ul");ul.innerHTML += "<li>" + data.title + "</li>";ul.innerHTML += "<li>姓名" + data.user.name + "</li>";ul.innerHTML += "<li>邮箱" + data.user.email + "</li>";document.body.appendChild(ul);}// 2.点击按钮发起一个基于JSONP的跨域请求var btn = document.querySelector("button");btn.addEventListener("click",function () {var script = document.createElement("script");script.src = "http://m.xt520.xyz/1.php?jsonp=handle&id=2";document.head.appendChild(script);},false);</script></body>
后台部分:
<?phpheader('content-type:text/html;charset=utf-8');$callback = $_GET['jsonp'];$id = $_GET['id'];// 模仿接口,根据查询条件返回不同的内容$users = ['{"name":"zhangsan","email":"youku@qq.com"}','{"name":"lisi","email":"yahoo@google"}','{"name":"tina","email":"keep@qq.com"}',];if (array_key_exists(($id-1),$users)) {$user = $users[$id-1];}$json = '{"title":"学生表","user":'.$user.'}';echo $callback . '(' . json_encode($json). ')';
效果图:

通过老师两个案例的讲解,我大概了解了跨域请求,能够做什么,它主要用在数据交互,一个页面引用另一个页面,用异步请求获取数据,实现数据的共享。跨域主要说的是AJAX请求无法完成,这个时候就用我们的CORS和JSONP技术来解决这个难题。感觉自己又学会了一个好东西,开心。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号