我正在尝试使用ajax
从xml文件中检索一些数据 <?xml version="1.0" encoding=UTF-8"?>
<user>
<u_idno>1</u_idno>
<u_name>nobody</u_name>
<u_srnm>nothing</u_srnm>
<u_role>linux</u_role>
</user>
<user>
<u_idno>2</u_idno>
<u_name>yesbody</u_name>
<u_srnm>something</u_srnm>
<u_role>administrator</u_role>
</user>
但是我收到了错误
Uncaught TypeError: Cannot read property 'getElementsByTagName' of null
我不确定为什么它会说null而且我一直疯狂地搜索我发现我做错了什么但是我一无所知。我的javascript如下
function f_ajax() {
var lv_request;
try {
lv_request = new XMLHttpRequest();
} catch (error) {
lv_request = new ActiveXObject("Microsoft.XMLHTTP");
}
lv_request.onreadystatechange = function() {
if(lv_request.readyState == 4 && lv_request.status == 200) {
lv_xml = lv_request.responseXML;
lv_row = lv_xml.getElementsByTagName("user");
lv_output = null;
for (lv_cnt = 0; lv_cnt < lv_row.length; lv_cnt++) {
lv_output = lv_output + lv_row[lv_cnt].childNodes[0].nodeValue;
}
document.getElementById("h2_ajax").innerHTML = lv_row;
}
}
lv_request.open("GET", "data.xml", true);
lv_request.send();
};
f_ajax();
答案 0 :(得分:1)
您的XML格式不正确。它缺少一个根,还有一些其他问题。试试这个:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<user>
<u_idno>1</u_idno>
<u_name>nobody</u_name>
<u_srnm>nothing</u_srnm>
<u_role>linux</u_role>
</user>
<user>
<u_idno>2</u_idno>
<u_name>yesbody</u_name>
<u_srnm>something</u_srnm>
<u_role>administrator</u_role>
</user>
</root>