PHP Ajax跨域問題解決方案代碼實(shí)例
本文通過設(shè)置Access-Control-Allow-Origin來實(shí)現(xiàn)跨域。
例如:客戶端的域名是client.runoob.com,而請(qǐng)求的域名是server.runoob.com。
如果直接使用ajax訪問,會(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è)域名訪問
指定某域名(http://client.runoob.com)跨域訪問,則只需在http://server.runoob.com/server.php文件頭部添加如下代碼:
header(’Access-Control-Allow-Origin:http://client.runoob.com’);
2、允許多個(gè)域名訪問
指定多個(gè)域名(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:*’);
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 基于 Python 實(shí)踐感知器分類算法2. Python如何批量生成和調(diào)用變量3. Python 中如何使用 virtualenv 管理虛擬環(huán)境4. ASP.NET MVC實(shí)現(xiàn)橫向展示購物車5. 通過CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動(dòng)畫特效6. Python獲取B站粉絲數(shù)的示例代碼7. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無效問題8. ASP.Net Core對(duì)USB攝像頭進(jìn)行截圖9. ASP.Net Core(C#)創(chuàng)建Web站點(diǎn)的實(shí)現(xiàn)10. python利用opencv實(shí)現(xiàn)顏色檢測(cè)
