通常状况下,在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"
>
|