php跨域访问java,案例:PHP Ajax 跨域最佳解决方案
本文通過設置Access-Control-Allow-Origin來實現跨域。
例如:客戶端的域名是edu.jb51.net,而請求的域名是edu.jb51.net。
如果直接使用ajax訪問,會有以下錯誤:
XMLHttpRequest cannot load http://edu.jb51.net/server.php. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://edu.jb51.net' is therefore not allowed access.
允許單個域名訪問
指定某域名(http://edu.jb51.net)跨域訪問,則只需在http://edu.jb51.net/server.php文件頭部添加如下代碼:
header('Access-Control-Allow-Origin:http://edu.jb51.net');
允許多個域名訪問
指定多個域名(http://edu.jb51.net、http://edu.jb51.net等)跨域訪問,則只需在http://edu.jb51.net/server.php文件頭部添加如下代碼:
$origin = isset($_SERVER['HTTP_ORIGIN'])? $_SERVER['HTTP_ORIGIN'] : '';
$allow_origin = array(
'http://edu.jb51.net',
'http://edu.jb51.net'
);
if(in_array($origin, $allow_origin)){
header('Access-Control-Allow-Origin:'.$origin);
}
允許所有域名訪問
允許所有域名訪問則只需在http://edu.jb51.net/server.php文件頭部添加如下代碼:
header('Access-Control-Allow-Origin:*');
總結
以上是生活随笔為你收集整理的php跨域访问java,案例:PHP Ajax 跨域最佳解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 消融手术多少钱啊?
- 下一篇: 狗年拜年php源码,2018狗年拜年词大