AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
现在大家写写了一个简单的ajax获取数据的小示例,希望能帮助需要帮助的。
html代码:
1 <table border="1" > 2 <!--因为在谷歌上会自动添加tbody标签,其他浏览器不会有这标签,所以添加tbody是为了选取元素时不会发生混乱。--> 3 <tbody> 4 <tr> 5 <th>日期</th> 6 <th>最高温度</th> 7 <th>最低温度</th> 8 <th>天气</th> 9 </tr> 10 </tbody> 11 </table>
javascript代码:
<script> //创建ajax对象 var xhr=new XMLHttpRequest(); //监听相应 xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ //数据获取成功 //JSON.parse把数组格式的字符串转换成真正的数组 var data=JSON.parse(xhr.responseText) for(var i= 0;data.length>i;i++ ){ var tr= document.createElement(‘tr‘); var dateTd = document.createElement(‘td‘); dateTd.innerHTML=data[i].date; var maxTd = document.createElement(‘td‘); maxTd.innerHTML=data[i].max_temperature; var minTd = document.createElement(‘td‘); minTd.innerHTML=data[i].min_temperature; var weatherTd = document.createElement(‘td‘); weatherTd.innerHTML=data[i].weather; //将td挂上tr上 tr.appendChild(dateTd); tr.appendChild(maxTd); tr.appendChild(minTd); tr.appendChild(weatherTd); document.getElementsByTagName("tbody")[0].appendChild(tr) } }else{ console.log(加载失败) } } } //发送请求 xhr.open("GET","weather.json","true"); xhr.send(null) </script>
json数据:
[{ "date":"2017-12-12", "max_temperature":40, "min_temperature":30, "weather":"天晴" },{ "date":"2017-12-13", "max_temperature":38, "min_temperature":20, "weather":"雨" },{ "date":"2017-12-14", "max_temperature":35, "min_temperature":25, "weather":"天晴" },{ "date":"2017-12-15", "max_temperature":30, "min_temperature":25, "weather":"小雨" },{ "date":"2017-12-16", "max_temperature":40, "min_temperature":32, "weather":"天晴" },{ "date":"2017-12-17", "max_temperature":25, "min_temperature":20, "weather":"阴" },{ "date":"2017-12-18", "max_temperature":39, "min_temperature":35, "weather":"阵雨" }]
效果:
时间: 2024-11-09 05:15:58