首页 > 解决方案 > 如何获取数据json

问题描述

我想用 JQUERY 获取 Json 数据,但我的变量未定义。


        var itech_centre='';
      
    $.each(data, function(key,value){
    
        itech_centre+='<tr>';
        itech_centre+='<td>'+value.c_com_nom+'</td>';
        itech_centre+='<td>'+value.c_adr_voie+'</br>'+value.c_com_cp+'</br>'+value.c_com_nom+'</td>';
        itech_centre+='<td>'+value.c_rdv_tel+'</td>';
        
        itech_centre+='</tr>';
    });
    
    $('#centreVaccination').append(itech_centre);
   
    
    });

这是我的 HTML

 <table class="table table-bordered table-striped" id="centreVaccination">
                            <tr>
                                <th>Centre</th>
                                <th>Adresse</th>
                                <th>Tel</th>
                                
                            </tr>

和我的链接 JSON:https ://www.data.gouv.fr/fr/datasets/r/d0566522-604d-4af6-be44-a26eefa01756

谢谢你的帮助!

标签: jqueryjsongetjson

解决方案


我想看看你是怎么设置的data。仅将该链接中的 json 设置为data不起作用,因为您尝试获取的值 (c_com_nom等) 嵌套在features数组下方和properties对象内部。

我会通过创建一个 var 来保存features数组,然后遍历每个功能并从属性对象中获取您想要的属性来解决这个问题。

示例(略带伪代码):

// Import json here
const features = data.features;
let rows = "";
features.forEach(feature => {
  let row = "<tr>";
  row += "<td>" + feature.properties.c_com_nom + "</td>"
  // ...
  row += "</tr>";
  rows += row;
}
// Append rows to your table

推荐阅读