JSONP与artTemplate模板引擎使用的示例–请求天气数据
前面两篇简单总结了 jsonp跨域请求的原理,以及artTemplate模板引擎的使用。所以做个简单的请求天气的例子。
不知道什么原因,昨天请求百度天气的数据老是报{“status”:240,”message”:”APP 服务被禁用”}的错误。所以就选择了聚合数据中的天气预报数据。与百度申请数据一样,聚合数据同样也是样申请AK的。
如图:
还记得jsonp是如何利用jQuery中的ajax方法请求数据的吗?忘了的话,点击这里查看
还记的artTemplate模板引擎的使用步骤吗,忘了的话点击这里
请求数据的过程中,我们要拿我们需要的数据。来看一下,当我发送ajax请求的时候,请求成功的时候,获得的数据:
success:function(data){
// 如果 不写 jsonpCallback 那么默认调用的是 success方法
console.log(data);
}
- 1
- 2
- 3
- 4
我们只需要获得 Object中的result中的future对象,获取方式
success:function (data) {
// 如果不写jsonpCallback 那么默认调用的是success方法
//console.log(data);
// 读取对象
var weatherResult = data.result;
console.log(weatherResult);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
怎样把future数据 合理的显示在html页面上呢,这就需要我们的artTemplate模板引擎啦。
<!--定义模板-->
<script type="text/template" id="template">
<table>
<%for(var key in future){%>
<tr>
<td><%= future[key].date%></td>
<td><%= future[key].week%></td>
<td><%= future[key].temperature%></td>
<td><%= future[key].weather%></td>
<td><%= future[key].wind%></td>
</tr>
<%}%>
</table>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
获得数据后,显示在页面中就可以啦。
给出完整的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>请求聚合数据天气</title>
<style type="text/css">
td{
border: 1px solid #0094ff;
}
</style>
</head>
<body>
<input type="button" value="查看未来6天的的天气预报" id="getWeather">
</body>
</html>
<!--引入jQuery-->
<script type="text/javascript" src="js/jquery.min.js"></script>
<!--导入引擎模板-->
<script type="text/javascript" src="js/template-native.js"></script>
<!--定义模板-->
<script type="text/template" id="template">
<table>
<%for(var key in future){%>
<tr>
<td><%= future[key].date%></td>
<td><%= future[key].week%></td>
<td><%= future[key].temperature%></td>
<td><%= future[key].weather%></td>
<td><%= future[key].wind%></td>
</tr>
<%}%>
</table>
</script>
<script type="text/javascript">
$('#getWeather').click(function () {
$.ajax({
url:"http://v.juhe.cn/weather/index?cityname=%E6%9D%AD%E5%B7%9E&dtype=json&format=1&key=70e01dc890b7247f9f757c9ccf91556f",
dataType:'jsonp',
success:function (data) {
// 如果不写jsonpCallback 那么默认调用的是success方法
//console.log(data);
// 读取对象
var weatherResult = data.result;
console.log(weatherResult);
// 调用模板
var str = template('template',weatherResult);
// console.log(str);
$('body').append(str);
}
});
});
</script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
结果展示:
是不是很简单啊!
转自:http://blog.csdn.net/qq_35800306/article/details/60957575