XMLHttpRequest cannot load file

通常狀況下,在chrome中運行一些含Ajax請求的界面原型時,會拋出下面錯誤: 

XMLHttpRequest cannot load file:///D:/eclipse/workspace/uiTest/WebContent/table1.html. Origin null is not allowed by Access-Control-Allow-Origin. 

從網上看到了解決辦法,記下來以備忘: 

給chrome加上啓動參數: 

--allow-file-access-from-files 

就能夠了(須要關閉全部chrome窗口重啓瀏覽器)。
html

XMLHttpRequest2 進行跨域訪問時須要服務器許可,不是任何域都接受跨域請求的。先來看一下從 Yahoo YQL 域返回的響應頭(Response Header ):web

1
2
3
4
5
6
7
8
HTTP/1.1 200 OK
Set-Cookie: AO="o=1&s=1&dnt=1"; Version=1; Domain=yahoo.com; Max-Age=630720000; Expires=Sat, 18-Jun-2033 10:07:41 GMT; Path=/
Access-Control-Allow-Origin: *
Cache-Control: public, max-age=899
Content-Type: text/xml;charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Date: Sun, 23 Jun 2013 10:07:40 GMT

注意裏面有一條標識 Access-Control-Allow-Origin:* ,這就表示容許跨域訪問,因此能夠正常訪問該域,而對於其餘沒有該標識的域就會出現禁止訪問提示。chrome

 

那麼如何設置呢?若是要接受跨域訪問請求,就必須在服務器端返回的資源中加入 Access-Control-Allow-Origin 頭標識, Access-Control-Allow-Origin 的值能夠是 URL 或 *,若是是 URL 則只會容許來自該 URL 的請求,* 則容許任何域的請求。好比,在 HTML 中能夠設置:跨域

1
< meta  http-equiv = "Access-Control-Allow-Origin"  content = "*" >

或 瀏覽器

1
< meta  http-equiv = "Access-Control-Allow-Origin"  content = "http://www.baidu.com:80" >
相關文章
相關標籤/搜索