1. 前言javascript
在進行網站開發的過程當中常常會用到第三方的數據,可是因爲同源策略的限制致使ajax不能發送請求,所以也沒法得到數據。解決ajax的跨域問題能夠使用jsonp技術php
2.代碼html
<!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已失效java
3.功能與效果jquery
3.1 功能ajax
首次加載,默認是廈門的天氣預報,輸入城市名並點擊天氣查詢按鈕則獲取該天氣的天氣預報json
3.2 效果圖api
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原理及使用(講得很通俗易懂)