您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

PHP Ajax 跨域问题最佳解决方案

2025/4/24 9:49:58发布18次查看
本文通过设置access-control-allow-origin来实现跨域。
例如:客户端的域名是client.runoob.com,而请求的域名是server.runoob.com。
如果直接使用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.
1、允许单个域名访问
指定某域名(http://client.runoob.com)跨域访问,则只需在http://server.runoob.com/server.php文件头部添加如下代码:
header('access-control-allow-origin:http://client.runoob.com');
2、允许多个域名访问
指定多个域名(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);}
3、允许所有域名访问
允许所有域名访问则只需在http://server.runoob.com/server.php文件头部添加如下代码:
header('access-control-allow-origin:*');
以上就介绍了 php ajax 跨域问题最佳解决方案,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product