PHP Ajax 跨域问题解决方案
PHP Ajax 跨域问题解决方案
通过设置`Access-Control-Allow-Origin`来实现跨域。
#### 例如:
客户端的域名是`client.web3.xin`,而请求的域名是`server.web3.xin`。
如果直接使用ajax访问,会有以下错误:
XMLHttpRequest cannot load http://server.web3.xin/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://client.web3.xin' is therefore not allowed access.
#### 1、允许单个域名访问
指定某域名 `http://client.web3.xin` 跨域访问,则只需在`http://server.web3.xin/server.php`文件头部添加如下代码:
header('Access-Control-Allow-Origin:http://client.web3.xin');
#### 2、允许多个域名访问
指定多个域名`client1.web3.xin`、`client2.web3.xin` 等跨域访问,则只需在 `server.web3.xin/server.php` 文件头部添加如下代码:
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
$allow_origin = array(
'http://client1.web3.xin',
'http://client2.web3.xin'
);
if(in_array($origin, $allow_origin)){
header('Access-Control-Allow-Origin:'.$origin);
}
#### 3、允许所有域名访问
允许所有域名访问则只需在 `http://server.web3.xin/server.php`文件头部添加如下代码:
header('Access-Control-Allow-Origin:*');