jQuery getJSON()获取数据值

时间:2017-09-09 22:51:44

标签: jquery getjson

这是一个外部'data.json'样本,格式如下:

    {
    "A": [{"title": "Accountant", "name": "Adam"}],
    "B": [{"title": "Beefeeter", "name": "Brandon"}],
    "C": [{"title": "Coder", "name": "Charles"}],
    "D": [{"title": "Doctor", "name": "David"}]
    }

这是它的JS部分,在//....

中有问题
    <script>
    $(document).ready(function(){
    $.getJSON("data.json", function(data){
        $('title').html(data....title); // What is the best way to access/get the value of title, say Beefeeter in B?
        $('name').html(data....name); // What is the best way to access/get the value of name, say Coder in C?
        .....
        });
    });
    </script>

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

简单地做

$.getJSON("data.json", function(data){
    $('title').html(data.B[0].title); // Beefeeter in B
    $('name').html(data.C[0].title); // Coder in C
    .....
    });

再看一遍,我不太清楚你的jquery选择器后面是什么&#39; title&#39;并且&#39; name&#39;。这些不是标准的HTML标记名称。您是否打算使用id="title"id="name"来引用元素?在这种情况下,选择器应该是$('#title')$('#name')

修改

如果您想访问实际的密钥&#39; A&#39;,&#39; B&#39;,&#39; C&#39;依此类推,您可以使用Object.entries()方法将它们与值一起列出:

var arr=Object.entries(data); // this turns data into an array arr
// You can then step through that array and use the key (obj[0]) itself
// and of course all properties of the object-type values (obj[1]):
arr.forEach(function(i,obj){ // i is just a numeric index: 0,1,2,...
  console.log( obj[0] /* A, B, C... */, obj[1].title, obj[1].name);
}

答案 1 :(得分:0)

如果您事先不知道您的类别(A,B,C等),唯一的方法是遍历json。

var list = jQuery.parseJSON( data );
for( var key in list) {
    $('title').html(list[key][0].title);
    $('name').html(list[key][0].name);
 }

此外,您可以添加尽可能多的div,因为您的json文件具有类别(如果需要)。