有一个这样的需求,并且最后要求是可点击的html静态文件,不要链接数据库
由于前端接触不多,最开始就尝试了一下之前比较熟练的ajax
var data = 0;
$.ajax({
url: '../sys.log',
type: 'GET',
data: data,
async:true,
dataType:"jsonp",
headers:{
'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
},
success :function (data) {
var str=new String();
var arr=new Array();
str=data;
arr=str.split('\n');
var li_str = "";
for(var i=0;i<arr.length;i++)
{
li_str = li_str+"<li class=\"layui-timeline-item\">\n" +
" <i class=\"layui-icon layui-timeline-axis\"></i>\n" +
" <div class=\"layui-timeline-content layui-text\">\n" +
" <h3 class=\"layui-timeline-title\">2019-03-3"+i+"</h3>\n" +
" <p>\n" +
arr[i]+
"\n" +
" </p>\n" +
" </div>\n" +
" </li>";
}
$("#ul_for").html(li_str);
},
});
然后发现从idea中直接打开可以,但是并不能通过静态文件读取到数据。 以为在idea中会自动把请求的地址变为http://localhost:63342/templates/system/log.html? 然而通过本地打开时是 file:///D:/1waibao/java-shop/shop-main/src/main/resources/templates/system/log.html 错误信息Access to XMLHttpRequest at 啊 from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. 由于通过链接直接访问本地文件被浏览器识别为十分危险的行为,好像就禁用了(火狐没有禁用),所以不通过服务器的话是没法用ajax访问的。
于是使用jsonp
<script>
function dataJson(data) {
console.log(data);
var li_str = "";
for(var i=0;i<data.data.length;i++)
{
li_str = li_str+"<li class=\"layui-timeline-item\">\n" +
" <i class=\"layui-icon layui-timeline-axis\"></i>\n" +
" <div class=\"layui-timeline-content layui-text\">\n" +
" <h3 class=\"layui-timeline-title\">"+data.data[i].date+"</h3>\n" +
" <p>\n" +
data.data[i].content+
"\n" +
" </p>\n" +
" </div>\n" +
" </li>";
}
$("#ul_for").html(li_str);
}
</script>
<!-- 引入要放在后面 -->
<script type="text/javascript" src="../sys.log?cb=dataJson"></script>
dataJson({
"status": "success",
"data": [
{
"date": "2015-01-04",
"content": "hello world"
},
{
"date": "2015-01-11",
"content": "这是sys.log的第二行"
},
{
"date": "2015-01-18",
"content": "这是sys.log的第三行"
}
]
})
成功获取
最关键的参考代码通过Ajax读取本地json文件,提示跨域的原因和解决方法
|