我在PHP中有一个API文件,它以JSON方式返回投票:
[{"10002" : "-1"},{"10003" : "2"}]
现在,我基本上需要能够在for循环中检查每个ID的投票,例如:
var parsed = JSON.parse(document.body.innerHTML); //[{"10002" : "-1"},{"10003" : "2"}] in string
for (i=0;i<parsed.length;i++)
{
var toAlter = document.getElementById(parsed[i].something); //I need to retrieve the ID somehow
toAlter.childNodes[2].innerHTML = parsed[i].something; //Need to retrieve the vote amount for the ID here
}
答案 0 :(得分:1)
尝试
var parsed = JSON.parse(document.body.innerHTML); //[{"10002" : "-1"},{"10003" : "2"}] in string
for (i=0;i<parsed.length;i++) {
var obj = parsed[i];
for(key in obj){
if(obj.hasOwnProperty(key)){
var toAlter = document.getElementById(key); //I need to retrieve the ID somehow
toAlter.childNodes[2].innerHTML = obj[key]; //Need to retrieve the vote amount for the ID here
}
}
}