1. 程式人生 > >Ajax請求:本地跨域的問題

Ajax請求:本地跨域的問題

HERE 請求參數 網絡 inf sublime 服務器 scheme 允許 ext

問題出現一:

1.Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

釋:請求源僅支持http、data、chrome、chrome-extension、https協議。

出現此問題是我將ajax請求的url寫成了以文本協議訪問,換句話說就是,涉及到 AJAX 操作的頁面“不能”使用文件協議訪問(文件的方式訪問)。

技術分享圖片

根據網絡上的解決方案:設置主流瀏覽器的請求參數或是在sublime編輯器中安裝插件,我都使用過了,還是沒有用。

後來查資料,涉及到了一個同源策略的概念,大概了解一下。

我將請求的url改成以http協議訪問,即:xhr.open(‘GET‘,‘http://localhost/Ajax/request-url.php‘)。

然後重新訪問,然而。。。。。

出現問題二:

2. No ‘Access-Control-Allow-Origin‘ header is present on the requested resource. Origin ‘null‘ is therefore not allowed access.

釋:在請求源裏沒有允許控制源的請求,即在服務器響應客戶端的時候,帶上Access-Control-Allow-Origin頭信息。

所以,我在請求源的頭部加入這行代碼:header("Access-Control-Allow-Origin: *");

然後繼續訪問,duang~ 問題解決啦。

Ajax請求:本地跨域的問題