【发布时间】:2022-10-14 14:59:48
【问题描述】:
我还需要将数组放入变量中。
我正在使用 .DataTable 进行分页,但它不接受使用 Javascript 从 xml 创建的表,根据这个https://datatables.net/forums/discussion/2689,我需要将我的 xml 转换为二维数组。
这是我的xml文件
<person>
<data>
<name>juan</name>
<city>tokyo</city>
<age>20</age>
<sex>m</sex>
</data>
<data>
<name>pedro</name>
<city>manila</city>
<age>22</age>
<sex>m</sex>
</data>
<data>
<name>maria</name>
<city>bangkok</city>
<age>23</age>
<sex>f</sex>
</data>
</person>
我的二维数组应该是这样的:
var person =[
["juan","tokyo","20","m"],
["pedro","manila","22","m"],
["maria","bangkok","23","f"],
];
这是我的 JavaScript 代码。输出显示在我的 html 页面上,但我不能将它用于 DataTable,这就是我需要将它存储在 javascript 数组中的原因。如何修改此代码以便将其放入变量而不是在 html 页面中显示?
function readperson(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status ==200){
writeperson(this);
}
}
xmlhttp.open("GET", "person.xml", true);
xmlhttp.send();
}
function writeperson(xml){
var x,i,xmlDoc,txt,ths,trs,tre,the;
xmlDoc = xml.responseXML;
var person =xmlDoc.getElementsByTagName("data");
var l = person.length;
var nodes = person[0].childNodes[0];
//var l3 = nodes[0].length;
var l2 = person[0].childNodes[0].nodeValue;
var arr = [];
//orders.length = 3 since two <data> tag
for(i=0; i < person.length; i++){
//will add brackets inside the array arr
arr.push([]);//example: if arr.push("hello") output is hello,hello,hello
arr[i][0]=person[i].getElementsByTagName("name")[0].childNodes[0].nodeValue
arr[i][1]=person[i].getElementsByTagName("city")[0].childNodes[0].nodeValue
arr[i][2]=person[i].getElementsByTagName("age")[0].childNodes[0].nodeValue
arr[i][3]=person[i].getElementsByTagName("sex")[0].childNodes[0].nodeValue
}
document.getElementById("person").innerHTML = arr;
}
当我使用 return 语句而不是 innerHTML 时,它不起作用。
我不知道我在做什么。我的教授甚至没有讨论 javascript 的基础知识,而是要求我们在一周内通过我们的输出。
更新我想到了。这是我的最终代码
$(document).ready(function () {
$.ajax({
type: "GET",
url: "person.xml",
dataType: "xml",
success: function (xml) {
const res = [];
$(xml).find("person > data").each(function (i, person) {
res.push([
$(this).find("name", person).text(),
$(this).find("city", person).text(),
$(this).find("age", person).text(),
$(this).find("sex", person).text(),
]);
});
$("#person_table").DataTable({
data: res,
columns: [
{ title: "Name" },
{ title: "Address" },
{ title: "Age" },
{ title: "Sex." },
],
});
},
});
});
【问题讨论】:
标签: javascript html jquery arrays