推进并支持浏览器进行跨站资源共享
在来源域的 AJAX 向目标域 发送请求时 浏览器会自动带上
Origh
头:
Oright : https://baike.baidu.com
目标域 会判断这个
Origh
值是否为自己预想的,如果是则返回 以下语句,表示同意跨域
Access-Control-Allow-Origh: https://baike.baidu.com
如果
Access-Control-Allow-Origh
之后是*
通配符 :
Access-Control-Allow-Origin:*
则表示任意域都可以往目标跨 。如果目标域不这样做,浏览器获得响应后没发现
Access-Control-Allow-Origh
头,就会报类似的权限错误:
Failed to load http://127.0.0.1/PHP/WebSecurity/CORS/input.php?id=1&Submit=Submit: No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'https://baike.baidu.com' is therefore not allowed access.
注意:如果设置了 允许跨域证书发送
Access-Control-Allow-Credentials:true
,那么Access-Control-Allow-Origh
就不能设置为*
通配符
header("Access-Control-Allow-Credentials:true");
实例:
//index.html
<!DOCTYPE html>
<html>
<body>
<form action = "input.php" method = "GET">
<input type="text" name="id">
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>
//input.php
<?php
header("Content-Type:text/html;charset = utf-8");
header("Access-Control-Allow-Origin:https://baike.baidu.com");//同意 https://baike.baidu.com 进行跨域
//Access-Control-Allow-Origin:*;表示任意域都可以向目标跨
$id = $_GET['id'];
if ($id) {
if ($id == 1)
{
echo "id = 1";
}
else if ($id == 2)
{
echo "id = 2";
}
else
{
echo "只有1,2";
}
}else {
echo "啥都没有";
break;
}
?>
//https://baike.baidu.com(来源域)内容
var val = new XMLHttpRequest();
val.open("GET","http://127.0.0.1/PHP/WebSecurity/CORS/input.php?id=1&Submit=Submit",true);
val.send();
console.log(val.responseText);
返回结果: id = 1
val.open("GET","http://127.0.0.1/PHP/WebSecurity/CORS/input.php?id=2&Submit=Submit",true);
val.send();
console.log(val.responseText);
返回结果: id = 2
val.open("GET","http://127.0.0.1/PHP/WebSecurity/CORS/input.php?id=3&Submit=Submit",true);
val.send();
console.log(val.responseText);
返回结果: 只有1,2