2016-04-25 16 views
0

以下のスクリプトはXMLHttpRequestを送信するはずですが、実行時にコンソールにUncaught TypeError: Cannot read property 'abort' of undefinedを投げています。これは宿題のためのもので、私は実行するように指示しているコードであることを確認するために3回チェックしました...私はエラーを見つけることができません。しかし、関係なく、私はこれがうまくいくようにしたい。GET XHRスクリプトでキャッチされないTypeErrorエラー。未定義のプロパティ 'abort'を読み取ることができません

「httpRequest」変数が未定義として登録されていることがわかります。割り当てられている関数内にあるのでしょうか?私は失われており、それを修正する方法を知らない。

// global variables 
var selectedCity = "Tucson, AZ"; 
var httpRequest = false; 
var weatherReport; 

function getRequestObject() { // Possible function responsible for error? 
    try { 
    httpRequest = new XMLHttpRequest(); 
    } 
    catch (requestError) { 
    document.querySelector("p.error").innerHTML = "Forecast not supported by your browser."; 
    document.querySelector("p.error").style.display = "block"; 
    return false; 
    } 
} 

function getWeather(evt) { 
    var latitude; 
    var longitude; 
    if (evt.type !== "load") { 
     if (evt.target) { 
     selectedCity = evt.target.innerHTML; 
     } else if (evt.srcElement) { 
     selectedCity = evt.srcElement.innerHTML; 
     } 
    } 
    if (selectedCity === "Tucson, AZ") { 
     latitude = 37.7577; 
     longitude = -122.4376; 
    } else if (selectedCity === "Chicago, IL") { 
     latitude = 41.8337329; 
     longitude = -87.7321555; 
    } else if (selectedCity === "Montreal, QC") { 
     latitude = 45.5601062; 
     longitude = -73.7120832; 
    } 
    if (!httpRequest) { 
    httpRequest = getRequestObject(); 
    } 
    httpRequest.abort(); // Where the error is thrown... 
    httpRequest.open("get","solar.php?" + "lat=" + latitude + "&lng=" + longitude, true); 
    httpRequest.send(null); 
    httpRequest.onreadystatechange = fillWeather; 
} 

function fillWeather() { 
    if(httpRequest.readyState === 4 && httpRequest.status === 200) { 
    weatherReport = JSON.parse(httpRequest.responseText); 
    } 
} 

var locations = document.querySelectorAll("section ul li"); 
for (var i = 0; i < locations.length; i++) { 
    if (locations[i].addEventListener) { 
     locations[i].addEventListener("click", getWeather, false); 
    } else if (locations[i].attachEvent) { 
     locations[i].attachEvent("onclick", getWeather); 
    } 
} 
if (window.addEventListener) { 
    window.addEventListener("load", getWeather, false); 
} else if (window.attachEvent) { 
    window.attachEvent("onload", getWeather); 
} 

答えて

0

あなたはそうhttpRequest = getRequestObject()が未定義に設定する、getRequestObject()return httpRequestに忘れてしまいました。

関連する問題