根据AJAX内容动态地为ID分配值

时间:2022-10-07 15:39:21

I have some javascript:

我有一些javascript:

eval('var incomingJSON =' + ajaxObj.responseText);
for (p in incomingJSON.common) {
    document.getElementById(p).value = incomingJSON.common.p;
} 

where ajaxObject.responseText is:

其中ajaxObject.responseText是:

{
    "common": {
        "item1": "1",
        "item2": "2",
        "item3": "3",
        "item4": "4",
        "item5": "5" 
    }
}

The following line works:

以下行有效:

document.getElementById(item1).value = incomingJSON.common.item1;

However, incomingJSON.common.p evaluates to "undefined". The left side of the assign works fine. What's the proper way to access the value in that object given the correct name?

但是,incomingJSON.common.p的计算结果为“未定义”。分配的左侧工作正常。在给定正确名称的情况下,访问该对象中的值的正确方法是什么?

1 个解决方案

#1


1  

I think you're looking for the bracket notation syntax:

我想你正在寻找括号表示法语法:

document.getElementById(p).value = incomingJSON.common[p];

#1


1  

I think you're looking for the bracket notation syntax:

我想你正在寻找括号表示法语法:

document.getElementById(p).value = incomingJSON.common[p];