- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>test</title>
- <script type="text/javascript" src="/statics/js/jquery-1.8.2.min.js"></script>
- <script type="text/javascript">
- var format = function(time, format) {
- var t = new Date(time);
- var tf = function(i) {
- return (i < 10 ? '0': '') + i
- };
- return format.replace(/yyyy|MM|dd|HH|mm|ss/g,
- function(a) {
- switch (a) {
- case 'yyyy':
- return tf(t.getFullYear());
- break;
- case 'MM':
- return tf(t.getMonth() + 1);
- break;
- case 'mm':
- return tf(t.getMinutes());
- break;
- case 'dd':
- return tf(t.getDate());
- break;
- case 'HH':
- return tf(t.getHours());
- break;
- case 'ss':
- return tf(t.getSeconds());
- break;
- }
- });
- }
- //上面函数是转换时间的,json里面格式是2015-06-17T15:00:00Z这样的
- $.ajax({
- type: "get",
- url:'pm25.php',//这个地方直接写第三方接口地址好像不行,跨域了,经本地文件转了一下,同时呢放php里面避免暴露key
- cache: false,
- dataType : "json",
- success: function(data){
- $.each(data, function(commentIndex, comment){
- var time_point= format(""+comment['time_point']+"", 'yyyy-MM-dd HH:mm:ss');//转换时间
- document.getElementById("primary_pollutant").innerHTML=""+comment['primary_pollutant']+"";
- document.getElementById("aqi").innerHTML=""+comment['aqi']+"";
- document.getElementById("quality").innerHTML=""+comment['quality']+"";
- document.getElementById("pm2_5").innerHTML=""+comment['pm2_5']+"";
- document.getElementById("time_point").innerHTML=""+time_point+"";
- });
- }
- });
- </script>
- </head>
- <body>
- <div>首要污染物:<span id="primary_pollutant"></span></div>
- <div>空气质量指数(AQI):<span id="aqi"></span></div>
- <div>空气状况:<span id="quality"></span></div>
- <div>颗粒物(粒径小于等于2.5μm)1小时平均:<span id="pm2_5"></span></div>
- <div>数据更新时间:<span id="time_point"></span></div>
- </body>
- </html>
js实时获取空气质量PM2.5