在項目開發中,常常會遇到跨域訪問資源,上傳圖片等,那麼這些都怎麼解決呢,下面簡單介紹一下ajax請求時,解決跨域問題。php
原文地址:小時刻我的博客 > http://small.aiweimeng.top/index.php/archives/29.htmlhtml
有時咱們在請求數據接口時,會看到控制檯中出現以下錯誤信息: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.
這句話意思說不能請求到資源;
若是客戶端請求其餘服務器的資源時咱們設置一下跨域;下面演示設置:apache
1.用php的方法在腳本中添加以下代碼:跨域
//容許單個域名訪問 header("Access-Control-Allow-Origin:http://www.yourdomain.com"); //或者下面這種,容許多個域名訪問 $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : ''; $allow_origin = array( 'http://www.yourdomain1.com', 'http://www.yourdomain2.com' ); if(in_array($origin, $allow_origin)) { header('Access-Control-Allow-Origin:'.$origin); } //或者下面這種,容許全部可訪問 header("Access-Control-Allow-Origin:*");
2.經過修改apache配置文件
首先編輯httpd.conf
找到 #LoadModule headers_module modules/mod_headers.so
去掉前面的 #
而後在獨立資源域名的虛擬主機添加一行:服務器
Header set Access-Control-Allow-Origin * #意思是對這個域名的資源進行訪問時,添加一個頭信息
重啓apache,再用ajax請求的時候就不會出現報錯了。dom