今天尝试前后端分离,用Ajax结合Vue框架获取springMVC生成RestfulAPI的数据,JSON数组是由一个List对象生成的。最后生成的JSON数据的格式大概是这样的,里面主要是天气数据的信息和站点信息:
[{“id”:null,“stationId”:“59488”,“year”:“1962”,“month”:null,“day”:null,“temAVG”:"22.5 ",“temH”:"35.3 ",“temL”:"6.0 ",“pre”:"1350.6 ",“prsAVG”:"1011.4 ",“prsH”:“缺测”,“prsL”:“缺测”,“rhuAVG”:"77.8 ",“rhuL”:“缺测”,“ssd”:"6.2 ",“winAVG”:"3.9 ",“winH”:“缺测”,“winD”:null,“winGustH”:“缺测”,“winGustD”:null,“stationInfo”:{“stationId”:“59488”,“province”:“广东”,“stationName”:“珠海”,“latitude”:null,“longitude”:null,“height”:null}},{“id”:null,“stationId”:“59488”,“year”:“1963”,“month”:null,“day”:null,“temAVG”:"22.8 ",“temH”:"37.1 ",“temL”:"4.7 ",“pre”:"1200.9 ",“prsAVG”:"1012.0 ",“prsH”:“缺测”,“prsL”:“缺测”,“rhuAVG”:"75.1 ",“rhuL”:“缺测”,“ssd”:"7.0 ",“winAVG”:"3.5 ",“winH”:“缺测”,“winD”:null,“winGustH”:“缺测”,“winGustD”:null,“stationInfo”:{“stationId”:“59488”,“province”:“广东”,“stationName”:“珠海”,“latitude”:null,“longitude”:null,“height”:null}}]
实现代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="../css/bootstrap.min.css"> <link rel="stylesheet" href="../css/historyyear.css"> <script src="../js/vue.js" type="text/javascript"> </script> </head> <body> <div id="weatherLists"> <div class="datatitle" align="center">{{weatherLists[0].stationInfo.stationName}}站1962-2018每年数据摘录</div> <table class="table table-bordered table-condensed" align="center" > <tr> <th rowspan="2">年</th> <th colspan="3">气温</th> <th colspan="3">气压</th> <th colspan="2">湿度</th> <th colspan="3">风速</th> <th rowspan="2">平均日照时数(h)</th> <th rowspan="2">年雨量(mm)</th> </tr> <tr> <th>最高气温(℃)</th> <th>平均气温(℃)</th> <th>最低气温(℃)</th> <th>最高气压(hpa)</th> <th>平均气压(hpa)</th> <th>最低气压(hpa)</th> <th>平均湿度(%)</th> <th>最低湿度(%)</th> <th>平均风速(m/s)</th> <th>最大风速(m/s)</th> <th>极大风速(m/s)</th> </tr> <tr v-for="weather in weatherLists"> <td v-text="weather.year"></td> <td v-text="weather.temH"></td> <td v-text="weather.temAVG"></td> <td v-text="weather.temL"></td> <td v-text="weather.prsH"></td> <td v-text="weather.prsAVG"></td> <td v-text="weather.prsL"></td> <td v-text="weather.rhuAVG"></td> <td v-text="weather.rhuL"></td> <td v-text="weather.winAVG"></td> <td v-text="weather.winH"></td> <td v-text="weather.winGustH"></td> <td v-text="weather.ssd"></td> <td v-text="weather.pre"></td> </tr> </table> </div> <script src="../js/jquery.js"></script> <script src="../js/bootstrap.js"></script> <script src="../js/index.js"></script> </body> </html>index.js中的内容
var vm=new Vue( { el:'#weatherLists', data:{ weatherLists:[], }, created:function(){ var self=this; $.ajax({ type: 'GET', dataType:'json', url: 'http://localhost/history/weather', success: function(data){ self.weatherLists=data; console.log(data); }, error:function(){ alert("获取失败"); } }) } })