使用ajax獲取用戶所在地的天氣


  1.要獲取用戶歸屬地的天氣,首先得獲取用戶所在的市區,

這里先獲取用戶的IP,通過IP獲取IP的歸屬地,從而得到用戶

地址。

獲取客戶端ip:

  js:

<scripttype="text/javascript" src="http://pv.sohu.com/cityjson?ie=utf-8"></script>

<scripttype="text/javascript">

  alert(returnCitySN.cip)

</script>

獲取ip歸屬地:

       淘寶接口:http://ip.taobao.com/service/getIpInfo.php?ip=183.129.210.50

{"code":0,"data":{"ip":"183.129.210.50","country":"中國","area":"","region":"浙江","city":"杭州","county":"XX","isp":"電信","country_id":"CN","area_id":"","region_id":"330000","city_id":"330100","county_id":"xx","isp_id":"100017"}}

  新浪接口:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=183.129.210.50

var remote_ip_info = {"ret":1,"start":-1,"end":-1,"country":"\u4e2d\u56fd","province":"\u6d59\u6c5f","city":"\u676d\u5dde","district":"","isp":"","type":"","desc":""};

 

  2.因為阿里雲提供了通過城市名(city)或者城市編號(cityId)

即可獲取天氣的API,從而獲取用戶歸屬地天氣

var city1;
$.ajax({
    //獲取客戶端 IP 和 歸屬地
url: "http://chaxun.1616.net/s.php?type=ip&output=json",
   contentType:'application/json;charset=urt-8', dataType:
"jsonp", success: function (data) { console.log('ip:' + data.Ip) console.log('歸屬地:' + data.Isp) var lcity = data.Isp.split(' ')[0]; //獲取短名稱,如淮安市 city1 = lcity.split('省')[1]; console.log(city1) //因為是異步刷新,所以兩個請求幾乎同時進行 $.ajax({ type: 'get', url: 'http://jisutqybmf.market.alicloudapi.com/weather/query', async: true, //設置驗證方式,設置請求頭 //1,APPCode headers: { Authorization: "APPCODE 你的APPCode" }, //2.APPSecret 暫時不能用 //headers: { AppKey: '你的APPKey', AppSecret :'你的APPSecret' }, data: { city: city1 }, success: function (result) { console.log(result['result']) //alert(result) }, error: function () { alert('error') } }); } });

 輸出結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM