PHP Ajax跨域問(wèn)題解決方案代碼實(shí)例
本文通過(guò)設(shè)置Access-Control-Allow-Origin來(lái)實(shí)現(xiàn)跨域。
例如:客戶端的域名是client.runoob.com,而請(qǐng)求的域名是server.runoob.com。
如果直接使用ajax訪問(wèn),會(huì)有以下錯(cuò)誤:
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、允許單個(gè)域名訪問(wèn)
指定某域名(http://client.runoob.com)跨域訪問(wèn),則只需在http://server.runoob.com/server.php文件頭部添加如下代碼:
header(’Access-Control-Allow-Origin:http://client.runoob.com’);
2、允許多個(gè)域名訪問(wèn)
指定多個(gè)域名(http://client1.runoob.com、http://client2.runoob.com等)跨域訪問(wèn),則只需在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、允許所有域名訪問(wèn)
允許所有域名訪問(wèn)則只需在http://server.runoob.com/server.php文件頭部添加如下代碼:
header(’Access-Control-Allow-Origin:*’);
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. idea導(dǎo)入maven項(xiàng)目的方法2. idea重置默認(rèn)配置的方法步驟3. IntelliJ IDEA安裝插件的方法步驟4. Docker 部署 Prometheus的安裝詳細(xì)教程5. IntelliJ IDEA設(shè)置自動(dòng)提示功能快捷鍵的方法6. idea給項(xiàng)目打war包的方法步驟7. idea設(shè)置代碼格式化的方法步驟8. IntelliJ IDEA調(diào)整字體大小的方法9. idea打開(kāi)多個(gè)窗口的操作方法10. 通過(guò)Django Admin+HttpRunner1.5.6實(shí)現(xiàn)簡(jiǎn)易接口測(cè)試平臺(tái)

網(wǎng)公網(wǎng)安備