2017-06-02 70 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>