本文通过设置Access-Control-Allow-Origin来实现跨域。

例如:客户端的域名是edu.jb51.net,而请求的域名是edu.jb51.net。

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

XMLHttpRequest cannot load http://edu.jb51.net/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://edu.jb51.net' is therefore not allowed access.
允许单个域名访问

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

header('Access-Control-Allow-Origin:http://edu.jb51.net');
允许多个域名访问

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

$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : ''; 
   
$allow_origin = array( 
    'http://edu.jb51.net', 
    'http://edu.jb51.net' 
); 
   
if(in_array($origin, $allow_origin)){ 
    header('Access-Control-Allow-Origin:'.$origin);      
}
允许所有域名访问

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

header('Access-Control-Allow-Origin:*');

原文来自:http://edu.jb51.net/w3cnote/code/php-ajax-cross-border.html

本文地址:https://www.linuxprobe.com/php-ajax-cross.html编辑:xiangping wu,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/