一、问题
使用浏览器访问本地文件时,一般地址是file://
开头的本地文件地址。
而访问远程文件时,一般地址是http://
或者https://
开头的地址,表示这个文件通过 http /https 协议访问的。
由于浏览器的同源策略保护,导致通过ajax请求本地文件时会出现跨域问题,如下所示:
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
console.log(myObj);
}
};
xmlhttp.open("GET", "./output.json", true);
xmlhttp.send();
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$.get("./output.json", function (data) {
//读进了data变量中
//接下来用到data的代码必须全部在此函数内部进行
console.log(data);
})
</script>
二、解决方法
2.1 JSONP方式
利用script/img/iframe标签的src不受同源策略影响的特性
<script type="text/javascript">
// 定义函数
function getJson(data) {
// data 就是要取的json数据
console.log(data);
}
</script>
//指定回调函数
<script src="./nav_distribution_byMonth.json?callback=getJson"></script>
将json文件的内容作为参数放入getJson函数中
2.2 运行本地Web服务器
我的电脑室Mac,自带有python,可以通过SimpleHTTPServer 模块启动服务器
⚠️mac自带是python 2.7,我安装了3.x版本,二者使用的模块不同
- 进入文件所在目录
- 在终端执行以下命令即可启动服务
# 如果你的 Python 版本是 3.X
python3 -m http.server
# 如果你的 Python 版本是 2.X
python -m SimpleHTTPServer
- 默认情况下,在本地 Web 服务器上的端口 8000 上运行工作目录中的内容。可以浏览器中输入 URL
http://localhost:8000
访问此服务器 - 此时会看到文件内容目录,点击即可查看想运行的文件。
在js文件中,将json文件地址改为localhost:8000开头的地址,之后再通过这种方式打开html页面
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$.get(
"http://localhost:8000/learn/%E6%AF%95%E8%AE%BE%E7%9B%B8%E5%85%B3/test/output.json",
function (data) {
//读进了data变量中
//接下来用到data的代码必须全部在此函数内部进行
console.log(data);
})
</script>