一、功能说明
使用ajax发送请求,获取data.json中的数据,并以表单的形式展示
二、代码
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>test_3</title>
<style>
h1 {
text-align: center;
}
table {
width: 1300px;
border-collapse: collapse;
margin: auto;
text-align: center;
}
table tr:nth-child(odd) {
background-color: #f5f5f5;
}
table tr:nth-child(even) {
background-color: #fff;
}
th {
background-color: yellow;
border: 1px solid red;
}
</style>
<head>
<!-- 若本地无Jquery,可使用CDN引入jQuery -->
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<script>
$(function () {
$.ajax({
url: '../data/data.json',
type: 'GET',
dataType: 'json',
})
.done(function (data) {
console.log("success");
putInfo(data);
})
.fail(function () {
console.log("error");
})
.always(function () {
console.log("complete");
});
})
//性别
function sex(i) {
var sex;
if (i === 1) {
sex = '男';
} else {
sex = '女';
}
return sex;
}
//是否已婚
function marry(i) {
var marry;
if (i === 1) {
marry = '是';
} else {
marry = '否';
}
return marry;
}
function putInfo(data) {
for (i in data) {
temp = data[i];
var str = "<tr>";
for (var x in temp) {
if (x === "性别") {
str += "<td class='td-item'>" + sex(temp[x]) + "</td>";
} else if (x === "婚姻") {
str += "<td class='td-item'>" + marry(temp[x]) + "</td>";
} else {
str += "<td class='td-item'>" + temp[x] + "</td>";
}
}
str += "</tr>";
$("table").append(str);//append jQuery方法。
}
}
</script>
</head>
</html>
<table id="tableinfo">
<tr>
<th>姓名</th>
<th>国家</th>
<th>城市</th>
<th>性别</th>
<th>部门</th>
<th>邮箱</th>
<th>岗位</th>
<th>学校</th>
<th>生日</th>
<th>是否已婚</th>
<th>月薪</th>
</tr>
</table>
三、解释
1、使用CDN引入JQuery的3种常用方式
①百度CDN
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
②Microsoft CDN
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
③Google CDN
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
2、打开浏览器后没有获取到json中的data,表格数据为空,打开控制台,看到如下报错:
table.html:1 Access to XMLHttpRequest at 'file:///D:/data/grid.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
初步断定,这应该是在说我的浏览器不支持file协议的。
解决方案(1)
打开谷歌浏览器的属性设置
在快捷方式下的【目标】后面加上: ‘ –allow-file-access-from-files’(注意 - - 前有一个空格)
然后关闭浏览器,重新打开即可
解决方案(2)
将代码文件和data.json文件放在tomcat的webapps下,修改url,直接在Tomcat中运行即可