Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:实际项目中会有一些封装好的跨域方法可以用, 更方便, 但理解原理会更好掌握它
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>跨域请求</button>
<h3 style="color: blueviolet;"></h3>
<script>
var btn = document.querySelector("button");
btn.onclick = function(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.responseText);
document.querySelector("h3").innerHTML=xhr.responseText;
}
};
xhr.open("get","http://www.qwe.demo/test.php",true);
xhr.send(null);
}
</script>
</body>
</html>
后端
<?php
header('Access-Control-Allow-Origin:http://www.php11.demo');
echo "跨域脚本返回的数据";
flush();
?>
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>跨域请求-JSONP</button>
<script>
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);
}
var btn = document.querySelector("button");
btn.onclick = function(){
var script = document.createElement('script');
script.src = "http://www.qwe.demo/test1.php?jsonp=handle&id=1";
document.head.appendChild(script);
}
</script>
</body>
</html>
<script>
</script>
后端
<?php
header('content-type:text/html;charset=utf-8');
$callback = $_GET['jsonp'];
$id = $_GET['id'];
$users = [
0=>'{"name":"zcx","email":"zcx@qq.com"}',
1=>'{"name":"zxc","email":"zxc@qq.com"}',
2=>'{"name":"cxz","email":"cxz@qq.com"}'
];
if(array_key_exists(($id-1),$users)){
$user = $users[$id-1];
}
$json = '{
"title":"用户信息",
"user": '.$user.'
}';
echo $callback .'('.json_encode($json).')';
?>
本节课我们学习了CORS跨域请求与JSONP跨域请求的知识,通过本节课的学习使我知道如何进行跨域请求,希望通过后续的学习应用于实际开发中。