Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:对于刚接触的同学来说, 有可能照抄都会抄不对, 克服这种现象没有捷径,唯有不断的重复, 我们都是这样学过来的, 相信你也行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>cors跨域请求</title>
</head>
<body>
<button>CORS跨域请求按钮</button>
<h2></h2>
<script>
//获取按钮
var btn = document.querySelector("button");
//获取点击事件
btn.addEventListener("click",function(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState === 4 && xhr.status === 200)
{
console.log(xhr.responseText);
//页面渲染
var h2 = document.querySelector("h2");
h2.innerHTML = xhr.response;
}
};
xhr.open("GET","http://127.0.0.7/0522/test1.php",true);
xhr.send(null);
},false);
</script>
</body>
</html>
<?php
//如果是ip,后免不需要加“/” 。
header('Access-Control-Allow-Origin:http://127.0.0.8');
//header('Access-Control-Allow-Origin:*');
echo "跨域CORS请求1111";
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CORS--跨域请求获取函数数据</title>
</head>
<body>
<!--动态生成请求-->
<button>动态按钮生成CORS跨域请求</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.account + "</li>";
ul.innerHTML += "<li>" + data.user.user + "</li>";
document.body.appendChild(ul);
}
var btn = document.querySelector("button");//获取按钮
//添加事件
btn.addEventListener('click',function(){
// 生成script标签
var script=document.createElement("script");
script.src="http://127.0.0.7/0522/test2.php?json=handle&id=2";
document.head.appendChild(script);
},false);
</script>
<!-- //函数在前,请求在后 固定写上-->
<!-- <script src="http://127.0.0.7/0522/test2.php?json=handle"></script>-->
</body>
</html>
<?php
$callback = $_GET['json'];
//echo $data;
$id=$_GET['id'];
$users = [
'{"account":"admin","user":"管理员"}',
'{"account":"super","user":"超级管理员"}',
];
//array_key_exists — 检查数组里是否有指定的键名或索引
if(array_key_exists(($id-1),$users)){
$user = $users[$id-1];
}
$json = '{
"title":"用户信息",
"user":'.$user.'
}';
echo $callback .'('. json_encode($json).')';