1. 前言
在進行網站開發的過程中經常會用到第三方的數據,但是由於同源策略的限制導致ajax不能發送請求,因此也無法獲得數據。解決ajax的跨域問題可以使用jsonp技術
2.代碼
<!DOCTYPE html>
<html>
<head>
<title>weatherSample</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//init, default: XiaMen
getWeatherInfo();
$("#cityName").text("城市: 廈門");
var tableHeaderData = $('table').parent().html();
function getWeatherInfo(){
$.ajax({
type : "get",
async: false,
url : "http://api.map.baidu.com/telematics/v3/weather?output=json&ak=6tYzTvGZSOpYB5Oc2YGGOKt8",
data:{
location:$("#city").val()||"廈門"
},
dataType: "jsonp",
jsonp:"callback", //請求php的參數名
jsonpCallback: "jsonhandle",//要執行的回調函數
success : function(data) {
if(data.status == 'success'){
$('#tip').html("");
var list = data.results;
var weatherDataArr = list[0].weather_data;
var items = "";
//init table of weatherInfo, just stay header data
$('table').html(tableHeaderData);
for(var i=0 ; i< weatherDataArr.length ;i++){
var date = weatherDataArr[i].date;
var dayPictureUrl = weatherDataArr[i].dayPictureUrl;
var nightPictureUrl = weatherDataArr[i].nightPictureUrl;
var temperature = weatherDataArr[i].temperature;
var weather = weatherDataArr[i].weather;
var wind = weatherDataArr[i].wind;
var item = "<tr><td>"+date+"</td>"
+ "<td><img src='"+dayPictureUrl+"'/></td>"
+ "<td><img src='"+nightPictureUrl+"'/></td>"
+ "<td>"+temperature+"</td>"
+ "<td>"+weather+"</td>"
+ "<td>"+wind+"</td>"
+ "</tr>";
items+=item;
}
$('table tr').after(items);
}
},
error:function(data){
//獲取失敗,打印出原因
$('#tip').html(`error reason=>{"status":220,"message":"APP Referer校驗失敗"}`)
}
});
}
$("button").click(function(){
getWeatherInfo();
})
$("input").change(function(){
$("#cityName").text("城市: " + $('#city').val());
})
});
</script>
</head>
<body>
<div style="margin-bottom:10px">
<input type="text" id="city" name="city"/>
<button style="margin-left:10px">天氣查詢</button>
</div>
<div id="cityName" style="margin-bottom:10px">城市: </div>
<div>
<table border="1px">
<tr>
<th>日期</th>
<th>白天</th>
<th>晚上</th>
<th>溫度</th>
<th>天氣</th>
<th>風力</th>
</tr>
</table>
</div>
<div id="tip" style="margin-bottom:10px"></div>
</body>
</html>
注:請求ak已失效
3.功能與效果
3.1 功能
首次加載,默認是廈門的天氣預報,輸入城市名並點擊天氣查詢按鈕則獲取該天氣的天氣預報
3.2 效果圖

4.說明
向百度天氣服務器發送請求的參數是:output=json&ak=6tYzTvGZSOpYB5Oc2YGGOKt8&callback=jsonhandle&location=%E5%8E%A6%E9%97%A8&_=1507712014958, %E5%8E%A6%E9%97%A8是廈門的utf-8編碼加%組成,好奇寶寶點這里
ajax返回來的data如下:

5.參考
2.簡單透徹理解JSONP原理及使用(講得很通俗易懂)
