0
我的問題似乎存在於LoadXML的子功能調用之間。看起來xml數據由於某種奇怪的原因而變爲null,我不知道如何解決這個問題。 Stackexchange似乎有許多類似的問題,但很多都沒有回答,或者他們的回答沒有幫助我的案子。無法讀取屬性'getElementsByTagName'爲null,發生了什麼?
function load() {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
var idname = document.getElementById("name").value;
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this); //it obtains it here...
LoadXML(this, idname);
}
};
xmlhttp.open("GET", "helper_database.xml", false);
xmlhttp.overrideMimeType('text/xml');
xmlhttp.send();
}
function LoadXML(xml, name) {
var x, i, xmlDoc, nametxt, areEqual;
xmlDoc = xml.responseXML;
nametxt = name;
console.log("HERE \n" + xmlDoc); //...but it becomes null.
x = xmlDoc.getElementsByTagName("name"); //this returns the error of "Cannot read property 'getElementsByTagName' of null"
console.log("muuttujan x eka: " + x[0]);
for (i = 0; i < x.length; i++) {
if (areEqual = xmlDoc.getElementsByTagName("name").toUpperCase() === nametxt.toUpperCase()) {
document.getElementById("ComFocus").value = x[i];
}
}
}
這裏是helper_database.xml
<Character>
<name>test</name>
<stats>
<Com>1</Com>
<Con>2</Con>
<Cun>3</Cun>
<Dex>4</Dex>
<Mag>5</Mag>
<Per>6</Per>
<Str>7</Str>
<Wil>8</wil>
</stats>
</Character>
這只是一個錯字(我很驚訝,你沒有得到的錯誤在Web控制檯中,但是我也沒有):XML格式錯誤:''請注意,結束標籤是'wil',而不是''。解決這個問題,它解析並且填入了'responseXML'。 –
我不建議用'console.log'手電筒在黑暗中徘徊,而是建議使用內置在瀏覽器中的全功能調試器打開燈光。使用它,你可以在你的'onreadystatechange'處理器中查看'this',並且看到它的'responseXML'屬性是'null'。 –
像T.J. Crowder寫道它是XML文件中的一種類型。此外,你會在平等支票上遇到問題。 'xmlDoc.getElementsByTagName(「name」)'是一個集合,所以不會有'.toUpperCase()'。你必須做類似'xmlDoc.getElementsByTagName(「name」)[i] .innerHTML.toUpperCase()'或更短'x [i] .innerHTML.toUpperCase()' –