为什么xhr.onreadystatechange没反应?

我想连一个天气预报的api, 但连接有问题.代码如下:

var data = document.getElementById("weather");
    console.log(1);
    function fun_weather(url){
        var xhr = new XMLHttpRequest()
        xhr.open("GET", url);
        console.log(2);
        console.log(xhr.readyState);    
        xhr.onreadystatechange = function(){
            console.log(3);

            switch(xhr.readyState){
            case 0:
                console.log("a");
                break;
            case 1:
                console.log("b");
                break;
            case 2:
                console.log("c");
                break;
            case 3:
                console.log("d");
                break;
            case 4:
                console.log("e");
                data.innerHTML = xhr.responseText;
                break;
        }
        console.log(4);

        xhr.send();

    }
}
fun_weather("https://free-api.heweather.com/s6/weather/forecast?location=chongqing&key=*");

console的信息:
console

可以看到程序到xhr.onreadystatechange就停了,难道是readystate没变吗?

阅读 4.5k
2 个回答

你把xhr.send放在onreadystatechange里面了, 请求没有发出去.

var data = document.getElementById("weather");
    console.log(1);
    function fun_weather(url){
        var xhr = new XMLHttpRequest()
        xhr.open("GET", url);
        console.log(2);
        console.log(xhr.readyState);    
        xhr.onreadystatechange = function(){
            console.log(3);

            switch(xhr.readyState){
                case 0:
                    console.log("a");
                    break;
                case 1:
                    console.log("b");
                    break;
                case 2:
                    console.log("c");
                    break;
                case 3:
                    console.log("d");
                    break;
                case 4:
                    console.log("e");
                    data.innerHTML = xhr.responseText;
                    break;
            }
            console.log(4);
        }
        xhr.send();
    }
fun_weather("https://free-api.heweather.com/s6/weather/forecast?location=chongqing&key=*");

你把这个代码放在 onreadstatechange 里面了,,,拿到外面来就行

    xhr.send();
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题