php和ajax跨域最佳解决方案
本文通过设置
Access-Control-Allow-Origin来实现跨域。
例如:客户端的域名是xxx.xxx.net,而请求的域名是xxx.xxx.net。
如果直接使用ajax访问,会有以下错误:
XMLHttpRequest cannot load http://xxx.xxx.net/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://xxx.xxx.net' is therefore not allowed access.
允许单个域名访问
指定某域名(http://xxx.xxx.net)跨域访问,则只需在
http://xxx.xxx.net/server.php文件头部添加如下代码:
header('Access-Control-Allow-Origin:http://edu.jb51.net');
允许多个域名访问
指定多个域名(http://xxx.xxx.net、http://xxx.xx.net等)跨域访问,则只需在
http://edu.jb51.net/server.php文件头部添加如下代码:
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
$allow_origin = array(
'http://xxx.xxx.net',
'http://xxx.xxx.net'
);
if(in_array($origin, $allow_origin)){
header('Access-Control-Allow-Origin:'.$origin);
}
允许所有域名访问
允许所有域名访问则只需在
http://xxx.xxx.net/server.php文件头部添加如下代码:
header('Access-Control-Allow-Origin:*');
相关推荐
-
「nginx」十、nginx的location配置详解2026-07-04 00:51:45 -

最清晰的mysql体系架构图 ,助你深度掌握MySQL开发管理,赢在大数据时代
最清晰的mysql体系架构图 ,助你深度掌握MySQL开发管理,赢在大数据时代2026-07-04 00:21:47 -
PHP读取Excel内的图片2026-07-03 00:07:41 -
mysql:Otter跨机房数据同步(单向)2026-07-03 00:02:48 -

在windows10系统下搭建IIS+PHP+MYSQL+phpMyAdmin服务器运行环境
在windows10系统下搭建IIS+PHP+MYSQL+phpMyAdmin服务器运行环境2026-07-02 00:15:08