课程表

PHP 基础教程

PHP 表单

PHP 高级教程

PHP 数据库

PHP XML

PHP 和 AJAX

PHP 参考手册

PHP 案例

工具箱
速查手册

AJAX 跨域问题

当前位置:免费教程 » 程序设计 » PHP

可以通过设置PHP文件的Access-Control-Allow-Origin来实现跨域。

例如:客户端的域名是client.w3xue.com,而请求的域名是server.w3xue.com。

如果直接使用ajax访问,会有以下错误:

XMLHttpRequest cannot load http://server.w3xue.com/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://client.w3xue.com' is therefore not allowed access.

1、允许单个域名访问

指定某域名(http://client.w3xue.com)跨域访问,则只需在http://server.w3xue.com/server.php文件头部添加如下代码:

header('Access-Control-Allow-Origin:http://client.w3xue.com');

2、允许多个域名访问

指定多个域名(http://client1.w3xue.com、http://client2.w3xue.com等)跨域访问,则只需在http://server.w3xue.com/server.php文件头部添加如下代码:

$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';  
  
$allow_origin = array(  
    'http://client1.w3xue.com',  
    'http://client2.w3xue.com'  
);  
  
if(in_array($origin, $allow_origin)){  
    header('Access-Control-Allow-Origin:'.$origin);       
} 

3、允许所有域名访问

允许所有域名访问则只需在http://server.w3xue.com/server.php文件头部添加如下代码:

header('Access-Control-Allow-Origin:*'); 
转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛