2015-09-06 86 views
-2

我寫在HTML表格顯示數據下面的代碼從數據庫中JSON格式返回顯示數據

success : function(data){ 
      alert("declaring variable"); 
      var output="<table id=tableStyle>"; 
      alert("creating output"); 
      output+="<tr>" + "<th>" + "REPORTSUITE_ID" + "</th>" + "<th>" + "REPORTSUITE_NAME" + "</th>" + "<th>" + "STAGING_DATABASE" + "</th>" + "<th>" + "DWH_DATABASE" + "</th>" + "</tr>"; 
      alert("starting for loop"); 
      for (var i in data) 
      { 
       output+="<tr>" + "<td>" + data[i].REPORTSUITE_ID + "</td>" + "<td>" + 
     "<button>"+data[i].REPORTSUITE_NAME + "</button>" + 
     "</td>" + "<td>" + data[i].STAGING_DATABASE + "</td>" + "<td>" + data[i].DWH_DATABASE + "</td>" + "</tr>"; 
      } 
      output+="</table>"; 
      alert ("displaying now "); 
      document.getElementById("placeholder").innerHTML=output; 
      } 

在JSON的數據格式如下所示:

[{"DWH_DATABASE": "abc", "REPORTSUITE_ID": 51, "REPORTSUITE_NAME": "C1","STAGING_DATABASE": "def", "TRANS_TABLE": "T1"}, 
{"DWH_DATABASE": "abc", "REPORTSUITE_ID": 49, "REPORTSUITE_NAME": "C2", "STAGING_DATABASE": "def", "TRANS_TABLE": "T2"}, 
{"DWH_DATABASE":"abc", "REPORTSUITE_ID": 40, "REPORTSUITE_NAME": "C3", "STAGING_DATABASE": "def", "TRANS_TABLE": "T3"}] 

當我執行上面的代碼中,我得到的結果如下:

REPORTSUITE_ID REPORTSUITE_NAME STAGING_DATABASE DWH_DATABASE 
undefined   undefined   undefined   undefined 
undefined   undefined   undefined   undefined 
undefined   undefined   undefined   undefined 

請告訴我如何d正確顯示數據

+0

你的'data'參數是一個JSON字符串還是已經被解析成一個Javascript對象? – jfriend00

+0

我認爲在循環內部,你應該通過'i'來訪問數據,比如'i.DWH_DATABASE'而不是'data [i] .DWH_DATABASE' – wallek876

+0

當你不在這裏附近時很難幫助你,以便及時回答我們提出的問題。 – jfriend00

回答

0

你必須首先解析JSON這樣你就可以對付它作爲一個對象不使用下面的代碼作爲第一行文字成功的方法:

data = JSON.parse(data); 
+0

我已經嘗試過這件事,但我仍然得到相同的輸出 – sk215

0

代碼是正確的,但要確保數據變量實際上包含數據。打印出來通過控制檯事先,你會看到裏面有什麼:

console.log("data:" + data); 
+0

我確實對數據警報,它提示正確的數據,所以數據正在返回 – sk215