本文通過設(shè)置Access-Control-Allow-Origin來實現(xiàn)跨域。
例如:客戶端的域名是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