首页 >后端开发 >php教程 >PHP Ajax 跨域问题最佳解决方案

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

WBOY
WBOY原创
2016-07-28 08:29:38884浏览

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

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

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

<span>XMLHttpRequest</span><span> cannot load http</span><span>:</span><span>//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.</span>
<p>1、允许单个域名访问</p><p>指定某域名(http://client.runoob.com)跨域访问,则只需在http://server.runoob.com/server.php文件头部添加如下代码:</p><pre class="brush:php;toolbar:false"><span>header</span><span>(</span><span>'Access-Control-Allow-Origin:http://client.runoob.com'</span><span>);</span>

2、允许多个域名访问

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

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

3、允许所有域名访问

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

<span>header</span><span>(</span><span>'Access-Control-Allow-Origin:*'</span><span>);</span>

以上就介绍了 PHP Ajax 跨域问题最佳解决方案,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn