ES6-Promise实时获取地址和天气问题
生活随笔
收集整理的這篇文章主要介紹了
ES6-Promise实时获取地址和天气问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
需要引用Jquery
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>HTML部分
<p><span class="add"></span><span class="weather"></span><span class="temp"></span><img src="" alt="" class="img" width="40"></p>JS部分
$(function(){//獲取網絡請求信息(根據不同的url返回不同的結果)function getApi(url){return new Promise((resolve,reject)=>{$.ajax({url:url,dataType:'jsonp',success:function(res){resolve(res);//如果請求成功可以兌現},error:function(err){reject(err);//如果失敗 拒絕失敗 給出拒絕理由}})})}//獲取地址var urlA = 'https://apis.map.qq.com/ws/location/v1/ip?key=CAABZ-AVSAQ-RDR5L-GTBDJ-HLA4O-A5FDB&output=jsonp&_=1593478015329';var urlB = 'https://wis.qq.com/weather/common?weather_type=observe|forecast_24h|air&source=pc';getApi(urlA).then(add=>{ //獲取地址console.log(add);var info = add.result.ad_info;//具體的地址信息$('.add').html(info.city);return getApi(urlB+`&province=${info.province}&city=${info.city}`)}).then(data=>{//獲取天氣console.log(data)$('.weather').html(data.data.observe.weather);$('.temp').html(data.data.observe.degree);$(".img").attr("src",`https://mat1.gtimg.com/pingjs/ext2020/qqindex2018/dist/img/weather/${data.data.observe.weather_code}.svg`);}).catch(err=>{ //失敗console.error(err)})})總結
以上是生活随笔為你收集整理的ES6-Promise实时获取地址和天气问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: R语言包(package)以及相关命令语
- 下一篇: 深度学习入门笔记(二):神经网络基础