小案例--封装jsonp
生活随笔
收集整理的這篇文章主要介紹了
小案例--封装jsonp
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
獲取地址和天氣
<!DOCTYPE html> <html><head><meta charset="utf-8"><title></title></head><body><h1>天氣</h1><p><span id="city"></span> <img src="" alt="" id="img" width="30"> <span id="weather"></span></p></body><script type="text/javascript">function jsonp(url,option={}){var jp=option.jp||"callback";//默認回調函數參數名var callback=option.callback||"jp";//默認回調函數參數值return new Promise((resolve,reject)=>{// 查看url是否有jp 沒有還要加上if(url.indexOf(jp)==-1){url+="&"+jp+"="+callback;}// 獲取callback的值var p1=url.indexOf(jp);var p2=url.indexOf("&",p1);p2==-1?p2=url.length:'';//如果查找不到設置p2位url.length;callback=url.slice(p1+jp.length+1,p2)// 動態的創建callback方法window[callback]=function(data){document.head.removeChild(script);resolve(data)}// 動態創建script標簽let script=document.createElement("script");script.src=url;document.head.append(script);// script加載失敗script.onerror=function(e){document.head.removeChild(script)reject(e)}})}var url1 = "https://apis.map.qq.com/ws/location/v1/ip?key=CAABZ-AVSAQ-RDR5L-GTBDJ-HLA4O-A5FDB&output=jsonp";var url2 = "https://wis.qq.com/weather/common?weather_type=observe|forecast_24h|air&source=pc&callback=jp";jsonp(url1) // 獲取地址.then(res=>{url2=url2+`&province=${res.result.ad_info.province}&city=${res.result.ad_info.city}`;city.innerHTML=res.result.ad_info.city;return jsonp(url2) //獲取天氣}).then(res=>{weather.innerHTML=res.data.observe.degree+"℃";img.src="https://mat1.gtimg.com/pingjs/ext2020/qqindex2018/dist/img/weather/"+res.data.observe.weather_code+".svg";})</script> </html>總結
以上是生活随笔為你收集整理的小案例--封装jsonp的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AE基础知识
- 下一篇: 调查显示,41%的下一代家族企业接班人希