2017-06-02 52 views
0

我有一个使用谷歌地图来选择一个点树种推荐,然后返回树种名单周围。这个函数的原始版本只是从csv文件打印值,但我已经调整它来搜索一个实际的数据库,平均条件分数,以及更多。尽管我对Javascript感到厌烦,但不知道如何打印出我的搜索结果。印刷JSON字典在Javascript

,我传送给页面的字典是这样的:

{ “species_list”:[{ “num_trees”:102, “species__trees_of_species__condition__score”:5, “species__id_species”:88, “avg_condition” :5.0, “species__name_scientific”: “杨梅X码头”},{ “num_trees”:828, “species__trees_of_species__condition__score”:4 “species__id_species”:88, “avg_condition”:4.0, “species__name_scientific”: “杨梅X码头”}] }

我现在的功能是这样的:

function if_gmap_updateInfoWindow() 
    { 
    var lng = gmapmarker.getPosition().lng().toFixed(6) 
    var lat = gmapmarker.getPosition().lat().toFixed(6) 
    infoWindow.setContent("Longitude: " + lng + "<br>" + "Latitude: " + lat); 
    document.getElementById("location-info").innerHTML = 'Lat/Long: ' + lat + ' x ' + lng; 

    // Call the model api 
    // TODO consts 
    $.ajax({  
     url: '/species-guide/json/' + lat + '/' + lng, 
     dataType: 'json', 
     type: 'get', 
     success:function(response){ 
      document.getElementById("species-recommendations").innerHTML = response['species_list'].join('<br>') 
      console.log(response) 
     } 
    }) 
} 
具有10

“响应[‘species_list’。加入(‘< BR>’)”我种的建议标签打印[对象的对象]清单,但我怎么告诉它打印的树种名称和值?

回答

0

,如果你想只是显示DOM中的直线上升JSON字符串,你可以这样做:

document.getElementById("species-recommendations").innerHTML = JSON.stringify(response.species_list, null, 2); 

重要的部分是:JSON.stringify(response.species_list, null, 2)

这将字符串化和“美化”的JSON响应,为你添加换行符,缩进2个空格。

如果你只是想打印键和值,你会通过递归每个对象都有循环:

resonse.species_list.forEach(species => { 
    Object.keys(species).forEach(key => { 
    // place `key` and `species[key]` in some element 
    }) 
}) 

问题用“香草” JS要做到这一点,是它显然是一个痛苦屁股。这就是为什么库和框架(如角)已经发明了:)

+0

我还在这里遇到了问题,在某些元素的“//地方‘键’和‘物种[关键]’,我不能让它不参考打印错误。例如,我喜欢这样的东西:'

' + species[species__name_scientific] + '

';那有意义吗? – TreeSF

0

试试这个

var html = '<pre>' + JSON.stringify(response['species_list'], null, '\t') + '</pre>'; 

为了有一个格式化输出,你需要在pre代码进行封装。

var response = {"species_list": [{"num_trees": 102, "species__trees_of_species__condition__score": 5, "species__id_species": 88, "avg_condition": 5.0, "species__name_scientific": "Arbutus x marina"}]}; 
 
document.getElementById("species-recommendations").innerHTML = '<pre>' + JSON.stringify(response['species_list'], null, '\t') + '</pre>';
<div id="species-recommendations"></div>