标签:grid 时间 str pil 文件 pre script 完成后 试验
ajax 怎么请求本地json数据 在前端开发的时间,我们暂时没有服务器,但是我们要用json 做试验的时候 需要用到本地json
先在本地建一个json文件 取名:text.json
内容如下:
{
"first": [
{
"name": "王小婷",
"nick": "祈澈菇凉"
},
{
"name": "安安",
"nick": "坏兔子"
},
{
"name": "编程微刊",
"nick": "简书"
}
]
}
——————————————————————————————————————————————————————————————————————————————————————————————————
然后建一个html 文件:
内容如下:
$.ajax({
url: "text.json", //json文件位置
type: "GET", //请求方式为get
dataType: "json", //返回数据格式为json
success: function(data) { //请求成功完成后要执行的方法
//each循环 使用$.each方法遍历返回的数据date
console.log("原努数据" + data)
$.each(data.first, function(i, item) {
console.log(item)
//由于对象是json 不能直接for()
})
}
})
现在可以利用ajax 的请求配合underscore.js 做一个前端填充案例:
完成代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<script src="cookie.js"></script>
<script src="./node_modules/jquery/dist/jquery.js"></script>
<script src="./underscore.js"></script>
<body>
<div id="text">
</div>
<!--这必须是一个script 且必须要有text/templath-->
<script type="text/template" id="moban">
<div class="grid">
<h4><%= name %></h4>
</div>
</script>
</body>
<script type="text/javascript">
var mobanstring = $("#moban").html();
var compiled = _.template(mobanstring);
$.ajax({
url: "text.json", //json文件位置
type: "GET", //请求方式为get
dataType: "json", //返回数据格式为json
success: function(data) { //请求成功完成后要执行的方法
//each循环 使用$.each方法遍历返回的数据date
console.log("原努数据" + data)
$.each(data.first, function(i, item) {
//现在item是一个{}对象了,乘下将对象填充到模板
console.log(item);//对象 类似于长成这样子 {"name": "111","nick": "000"}
var compiledstring = compiled(item);
$("#text").append($(compiledstring));
})
}
})
</script>
</html>
标签:grid 时间 str pil 文件 pre script 完成后 试验
原文地址:https://www.cnblogs.com/fgxwan/p/12153710.html