报错信息:
Access to XMLHttpRequest at 'file:///C:/Users/Administrator/Desktop/111/data/array.txt' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
报错方式:Chrome浏览器打开本地js文件用datatables插件的ajax方法访问本地的obj.txt文件。
代码如下:
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
</body>
<script src="http://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
$("#example").DataTable({
"ajax": "data/obj.txt",
"columns": [{
"data": "name"
}, {
"data": "position"
}, {
"data": "office"
}, {
"data": "extn"
}, {
"data": "start_date"
}, {
"data": "salary"
}]
});
});
</script>
报错分析:
1.判断为ajax的跨域访问问题
2.本地jsp没有通过服务器直接ajax中用jsonp访问本地js,使用file协议!
3.原以为能解决跨域问题,但是上面的报错信息就已经说明了,ajax跨域只支持这些协议框架:http,https,data,chrome(Chrome浏览器),chrome-extension(Chrome扩展插件),chrome-extension-resource(Chrome扩展资源),就是没有file协议!
百度到的解决方法大多都是说在google桌面图标右键—属性—快捷方式标签页—目标(就是google浏览器的安装路径)中路径后面添加" --allow-file-access-from-files",(注意前面有空格)。
或者找到谷歌浏览器chrome.exe安装路径复制下来,我的是E:\Google\Application\chrome.exe,再打开cmd,直接输入命令
"E:\Google\Application\chrome.exe" --allow-file-access-from-files
但是上述方法并没有解决我的报错,用Firefox不会报错,也就是说Filefox支持file协议下的AJAX请求。但是我依旧更喜欢强大的谷歌。
然后一刹那间灵光一闪,配置一个本地http服务器试试。
对于一些刚入门的同学,配一个HTTP服务器(比如Apache、IIS等)比较繁琐,但是我们可以通过插件来配置,比如我用的是VSCode,
1.打开VsCode的插件安装功能,在左侧的最底部位置,
2.接着在搜索框中输入live server,应该是搜索到的第一个,然后点击安装,
3.安装完成后点击重新加载(reload),重新启动vscode后,软件的右下角就会出现一个go live 的状态栏,这个就是启动刚刚安装的插件开关,
4.点击启动服务器,会自动运行系统默认的浏览器,默认的端口号是5500,到这里服务器就能跑起来了,运行我们的文件,报错已经消失。
回到VsCode再次点击即可关闭服务器。
默认是5500端口,那么万一端口冲突呢,或者我们需要自己设置端口呢,接下来就简单介绍下如何设置服务器的端口和代理。当然如果端口冲突,插件会自动启动其他端口的,这个大家不必担心,放心使用即可。
1.点击左下角的管理-设置,(或者点击左上角的文件--首选项--设置)
2.搜索关键字live server,往下找,我们可以找到live server的相关设置
liveServer.settings.port 是设置端口号的
liveServer.settings.proxy是设置代理的。
其他的设置可以自行查看。