本文通过设置Access-Control-Allow-Origin来实现跨域。
例如:客户端的域名是this.com,而请求的域名是that.com。
如果直接使用ajax访问,会有以下错误:
XMLHttpRequest cannot load http:/that.com/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://this.com' is therefore not allowed access.
- 允许单个域名访问
指定某域名(http://this.com)跨域访问,则只需在http://that.com/server.php文件头部添加如下代码:
header('Access-Control-Allow-Origin:http://this.com');
- 允许多个域名访问
指定多个域名(http://this1.com、http://this2.com等)跨域访问,则只需在http://that.com/server.php文件头部添加如下代码:
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
$allow_origin = array(
'http://this1.com',
'http://this2.com'
);
if(in_array($origin, $allow_origin)){
header('Access-Control-Allow-Origin:'.$origin);
}
- 允许所有域名访问
允许所有域名访问则只需在http://that.com/server.php文件头部添加如下代码:
header('Access-Control-Allow-Origin:*');
eg:
这样就可以允许所有地址跨域请求了

image.png