2012-09-06 67 views
0

我想用jQuery填充json數據表格。但div內容保持專有。請幫我找一個錯誤。數組list包含數據(我用console.log(list)檢查了它)。此外,list['Var1']list['Var2']指的是由密鑰Var1Var2指定的值。問題正是在jQuery中。使用jQuery填充json數據的表格

function loadData() { 
    $.getJSON(
       'modules/getData.php', 
     function(data) {  
        var list = data.flights; 
        var textToInsert = ''; 
        console.log(list); 
        for (var i = 0; i < list.length; i += 1) { 
         textToInsert[i++] = '<tr><td>'; 
         textToInsert[i++] = list['Var1']; 
         textToInsert[i++] = '</td>' ; 
         textToInsert[i++] = '<td>'; 
         textToInsert[i++] = list['Var2'];                
         textToInsert[i++] = '</td> </tr>' ;    
        } 
        $('#flights_table tbody').append(textToInsert.join('')); 
       } 
    );    
} 

<div id="flights_table" style="display:none;"> 
    <table id="newspaper-b" border="0" cellspacing="2" cellpadding="2" width = "100%"> 
         <thead> 
          <tr> 
           <th scope="col">Var1</th> 
           <th scope="col">Var2</th> 
          </tr> 
         </thead> 
         <tbody></tbody> 
    </table> 
</div> 

訪問getdata.php

$list = array(); 
//fill the list using 'keys' and 'values' 
    echo json_encode(array('flights' => $list)); 
    die(); 

UDPATE: list.length是包括在內。但螢火蟲還是說

TypeError: textToInsert.join is not a function

SOLUTION:的解決方案是使用:

for (var i = 0; i < list.length; i++) { 
         aux = list[i]; 
         textToInsert += '<tr><td>'; 
         textToInsert += aux.Var1; 
} 
+0

這不是一個功能,因爲它是一個串。你把它聲明爲'var textToInsert ='''。你正在使用它作爲一個數組,所以把它聲明爲一個數組。 –

回答

0

在你的for循環for (var i = 0; i <length; i += 1)

你們不是說什麼長!它應該是list.length

此外,你應該聲明textToInsert作爲數組不是字符串,如果你想使用它作爲這樣

textToInsert = []; 
+0

Thx,我更新了我的代碼,但是Firebug仍然說:TypeError:textToInsert.join不是函數 –

+0

查看我更新的答案,還可以發佈'console.log(list);'的輸出嗎?這可能也有幫助 – hsalama

0

嘗試

var textToInsert = new Array();