PHP Ajax跨域問題解決方案代碼實例
本文通過設(shè)置Access-Control-Allow-Origin來實現(xiàn)跨域。
例如:客戶端的域名是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:*’);
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. React+umi+typeScript創(chuàng)建項目的過程2. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附json.min.asp3. php測試程序運行速度和頁面執(zhí)行速度的代碼4. php網(wǎng)絡安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究5. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析6. 無線標記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁7. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析8. ASP中常用的22個FSO文件操作函數(shù)整理9. SharePoint Server 2019新特性介紹10. 三個不常見的 HTML5 實用新特性簡介
