鍍金池/ 問答/HTML/ 為什么xhr.onreadystatechange沒反應(yīng)?

為什么xhr.onreadystatechange沒反應(yīng)?

我想連一個天氣預(yù)報的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沒變嗎?

回答
編輯回答
愚念

你把xhr.send放在onreadystatechange里面了, 請求沒有發(fā)出去.

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=*");
2018年2月9日 19:52
編輯回答
骨殘心

你把這個代碼放在 onreadstatechange 里面了,,,拿到外面來就行

    xhr.send();
2018年9月16日 04:48