接入 PM2.5 數(shù)據
數(shù)據來源
http://pm25.in
接入方式
使用 Jquery 具被,直接請求數(shù)據拆魏,使用 jsonp 完成Ajax的跨域請求
代碼示例
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PM2.5調用頁面</title>
</head>
<body>
<div id="pm2_5">
</div>
<br />
注:返回數(shù)組中多一條記錄 監(jiān)測點為:null 声邦?
<script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function()
{
//官網為 http://www.pm25.in/ 調用pm2.5 返回 json
//url中 city 為 城市名邀泉,token 為 申請的AppKey(官網API頁面右側申請)
var url = "http://pm25.in/api/querys/pm2_5.json?city=北京&token=7rMwJqMxrmuDRFsAxBqP";
$.ajax({
type: 'POST',
url: url,
dataType : "jsonp",// 將dataType屏蔽后會運行error方法
success: function(json){
//遍歷網站返回的pm2.5數(shù)據
$("#pm2_5").append("<table>");
$("#pm2_5").append("<tr><td width='200px'>監(jiān)測點</td><td width='200px'>PM2.5</td><td width='200px'>等級</td><td width='200px'>監(jiān)測時間</td></tr>");
$.each(json, function (i, point){
$("#pm2_5").append("<tr><td>"+json[i].position_name+"</td><td>"+json[i].pm2_5+"</td><td>"+json[i].quality+"</td><td>"+json[i].time_point+"</td></tr>");
})
$("#pm2_5").append("</table>");
},
error:function(exception){
alert('調用失斅蚩摺唯灵!異常狀態(tài)文本:'+exception.statusText);
}
});
})
</script>
</body>
</html>
補充
Ajax的跨域請求有兩類解決方案 jquery.ajax jsonp 格式和 jquery.getScript 方式贾铝。
詳細參考:http://julying.com/jQuery-1.6-api/#p=jQuery.ajax