我已经看了半天才解决这个问题,但似乎没什么用。我想使用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以动态填充输入字段,所以像(请注意??字段??和??字段值是我需要知道的):
<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>
我知道如何使用数据[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');
});
});
答案 0 :(得分:2)
如果我不理解你,那可能就是答案。
$.each(data, function(index) {
$.each(data[index] ,function(key,value){
console.log("key :" + key + " value :" + value );
})
}) //END PARSE
key
变量是您要求的答案。