js 就天氣預報接口調用 實例

實例

 $.ajax({
            type: 'GET',
            url: 'https://www.tianqiapi.com/api/',
            data: 'version=v1&city=上海',
            dataType: 'JSON',
            error: function () {
                alert('網絡錯誤');
            },
            success: function (res) {
                var aa='<li>City: ' + res.city + '</li><li>Weather: ' + res.data[0].wea + '</li><li>Tips: ' + res.data[0].air_tips + '</li>';
                console.log(aa);
                var bb=1;
                // 遍歷數組
                for (var i = 0; i < res.data[0].hours.length; i++) {
                   bb+='<li>' + (i + 1) + ': 時間: ' + res.data[0].hours[i].day + ' 氣溫: ' + res.data[0].hours[i].tem + ' </li >';
                }
                 console.log(bb);
            }
        });

摘抄事例

var getNJWeather = function(){
    var mainBox = dojo.byId('portal_weather');
    mainBox.innerHTML="正在加載天氣信息,請稍候...";
    var jsonpArgs = {
        //地址
        url:  'http://weather.news.qq.com/js/gn_24.js',
        //超時時間
        timeout: 10000,
        //阻止緩存
        preventCache: true,
        load: function(data) {
            if(data){
                var weather = v.find("南京").w;
                if(weather){
                    weather = weather.replace(/城市:|\<br\/>|天氣:|溫度:|風力:/g," ");
                    mainBox.innerHTML = weather;
                }else{
                    mainBox.innerHTML = "加載的天氣信息有誤";
                }
          }else{
              mainBox.innerHTML = "沒有加載到天氣信息";
          }
       },
       error: function(error) {
          mainBox.innerHTML = "加載天氣信息超時";
       }
    };
    //使用dojo的jsonp調用
    dojo.io.script.get(jsonpArgs);
 };
 dojo.addOnLoad(function(){
    getNJWeather();
 });

API
https://www.kancloud.cn/ccjin/yingq/603579

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章