-1

我已经寻找了半天的解决方案,但似乎没有任何效果。我想使用 jQuery 从一个基本上看起来像这样的文件加载 JSON:

[{"field_a":"1","field_b":"1000","field_c":"PRINCIPAL CASH"},
{"field_a":"2","field_b":"2000","field_c":"TRUST ASSETS"},
{"field_a":"3","field_b":"3000","field_c":" BONDS"},
{"field_a":"4","field_b":"4000","field_c":" STOCKS"}]

我想要做的是解析 JSON 以动态填充输入字段,例如(请注意 ??field?? 和 ??field value?? 是我需要知道的):

<input id="field_a" name="field_a" value="">
<input id="field_b" name="field_b" value="">
<input id="field_c" name="field_c" value="">

<script type="text/javascript">
$(function(){

    //GET THE JSON DATA
    $.getJSON('../coreScripts/selectGeneralLedger.php', function(data) {

       //PARSE TO FIELDS
        $.each(data, function(index) {  
            $("#"+data[index].??field name??).attr("value",  data[index].??field value??);
        }) //END PARSE

     }); //End get JSON 

});
</script>

我知道如何使用 data[index].field_a 手动访问字段值,但我一生都无法弄清楚如何动态解析它。任何帮助,将不胜感激。

更新*

adeneo 在评论中给了我下面的解决方案。简单的。这是脚本:

var data = [{"field_a":"1","field_b":"1000","field_c":"PRINCIPAL CASH"}, {"field_a":"2","field_b":"2000","field_c":"TRUST ASSETS"}, {"field_a":"3","field_b":"3000","field_c":" BONDS"}, {"field_a":"4","field_b":"4000","field_c":" STOCKS"}];


$.each(data, function(index, obj) {  
    $.each(obj, function(key, value) {
        $('<input />', {id: key, name:key, value:value}).appendTo('body');
    });
});
4

1 回答 1

1

如果我不明白你,它可以是一个答案。

 $.each(data, function(index) {  
     $.each(data[index] ,function(key,value){
            console.log("key :" + key + " value :" + value );
     })
 }) //END PARSE

key变量是您要求的答案。

于 2013-10-01T20:32:03.177 回答