本文經過設置Access-Control-Allow-Origin來實現跨域。php
例如:客戶端的域名是client.runoob.com,而請求的域名是server.runoob.com。ajax
若是直接使用ajax訪問,會有如下錯誤:跨域
XMLHttpRequest cannot load http://server.runoob.com/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://client.runoob.com' is therefore not allowed access.spa
指定某域名(http://client.runoob.com)跨域訪問,則只需在http://server.runoob.com/server.php文件頭部添加以下代碼:server
header('Access-Control-Allow-Origin:http://client.runoob.com');
指定多個域名(http://client1.runoob.com、http://client2.runoob.com等)跨域訪問,則只需在http://server.runoob.com/server.php文件頭部添加以下代碼:
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : ''; $allow_origin = array( 'http://client1.runoob.com', 'http://client2.runoob.com' ); if(in_array($origin, $allow_origin)){ header('Access-Control-Allow-Origin:'.$origin); }
容許全部域名訪問則只需在http://server.runoob.com/server.php文件頭部添加以下代碼:域名
header('Access-Control-Allow-Origin:*');