不啰嗦,直接上代碼: 1、在瀏覽器輸入網址:http://api.asilu.com/weather/?callback=getname&city=深圳 你會看到如下結果:他返回的是json數據 整理之後是這樣的: 2、怎樣才能獲取上述json的數據呢?很簡單: 3、效果圖是這樣的: 4、完畢。 ...
不啰嗦,直接上代碼:
1、在瀏覽器輸入網址:http://api.asilu.com/weather/?callback=getname&city=深圳
你會看到如下結果:他返回的是json數據
/** api.asilu.com **/getname({"city":"深圳","pm25":"28","weather":[{"date":"周一 09月10日","icon1":"day\/duoyun","icon2":"night\/duoyun","weather":"多雲","wind":"無持續風向微風","temp":"31 ~ 25℃"},{"date":"周二","icon1":"day\/duoyun","icon2":"night\/duoyun","weather":"多雲","wind":"無持續風向微風","temp":"31 ~ 27℃"},{"date":"周三","icon1":"day\/leizhenyu","icon2":"night\/leizhenyu","weather":"雷陣雨","wind":"東風4-5級","temp":"31 ~ 26℃"},{"date":"周四","icon1":"day\/zhenyu","icon2":"night\/zhenyu","weather":"陣雨","wind":"東風3-4級","temp":"30 ~ 26℃"}],"date":"2018-09-10","id":"101280601","t":1536508800});
整理之後是這樣的:
/** api.asilu.com **/ getname({ "city": "深圳", "pm25": "28", "weather": [{ "date": "周一 09月10日", "icon1": "day\/duoyun", "icon2": "night\/duoyun", "weather": "多雲", "wind": "無持續風向微風", "temp": "31 ~ 25℃" }, { "date": "周二", "icon1": "day\/duoyun", "icon2": "night\/duoyun", "weather": "多雲", "wind": "無持續風向微風", "temp": "31 ~ 27℃" }, { "date": "周三", "icon1": "day\/leizhenyu", "icon2": "night\/leizhenyu", "weather": "雷陣雨", "wind": "東風4-5級", "temp": "31 ~ 26℃" }, { "date": "周四", "icon1": "day\/zhenyu", "icon2": "night\/zhenyu", "weather": "陣雨", "wind": "東風3-4級", "temp": "30 ~ 26℃" }], "date": "2018-09-10", "id": "101280601", "t": 1536508800 });
2、怎樣才能獲取上述json的數據呢?很簡單:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ajax</title> </head> <body> <h1>天氣查詢</h1> <input type="text" placeholder="請輸出你的地址" id="tel"/> <button id="ajax">確定</button> <p><span id="reslut"></span></p> <script type="text/javascript" src="jquery-3.3.1/jquery-3.3.1.js"></script> <script type="text/javascript"> $(function(){ $('#ajax').on('click',function(){ var $telValue=$('#tel').val(); if($telValue=="") { alert('不能為空!'); return; } $.ajax({ type: 'GET', dataType:'jsonp', url: 'http://api.asilu.com/weather/?callback=getname&city='+$telValue, success: function(data){ var reslutData=data; console.log(reslutData); $('#reslut').text("你查詢的是:"+reslutData.city+","+"明天的天氣是:"+reslutData.weather[0].weather); } }) }) }) </script> </body> </html>
3、效果圖是這樣的:
4、完畢。