本文透過設定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教程有興趣的朋友有所幫助。