JS 获取天气数据(实时)

根据用户选择的城市,显示这个城市的天气信息。api接口:http://wthrcdn.etouch.cn/weather_mini?city=深圳 注意:这个接口已经服务端打破了同源。

效果:

JS 获取天气数据(实时)_第1张图片
Paste_Image.png

html :




    
        
        
        
    

    
        请选择你所在的城市:
        
        未来五天的天气
        

JS ajax方法:

ajax = {
    /*使用get方法进行ajax请求*/
    get: function (option){
        if (!option.url) return; //
        if (typeof option.onSuccess != "function") return;

        var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")
        xhr.open("GET", option.url, true);
        xhr.onreadystatechange = function (){
            if (xhr.readyState == 4){
                if (xhr.status == 200){
                    option.onSuccess(xhr.responseText);
                }else{
                    if (typeof option.onFail == "function"){
                        option.onFail(xhr.responseText);
                    }   
                }
            }
        }
        xhr.send(null);
    },
    /*使用post方式进行ajax请求*/
    post: function (option){
        if (!option.url) return; //
        if (typeof option.onSuccess != "function") return;
        var xhr = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject("Micosoft.XMLHTTP")
        xhr.open("POST",option.url,true);
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                if(xhr.status == 200){
                    option.onSuccess(xhr.responseText);
                }else{
                    if(typeof option.onFail == "function"){
                        option.onFail(xhr.responseText);
                    }
                }
            }
        }
        //如果是使用的post提交表单数据,需要添加这个请求头
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.send(option.data);
    }
}

你可能感兴趣的:(JS 获取天气数据(实时))