2016-05-30 44 views
-3

我的json數組就像那個在html頁面中接收到的數據,它如何顯示在表中?意味着迭代.plz的幫助?我是新的 。如何json數組迭代可以完成?

[ 
    {"studentId":"1001259101","firstName":"RAKESH","lastName":"DALAL","year":"2012","course":"BSC"}, 
    {"studentId":"1001259101","firstName":"RAKESH","lastName":"DALAL","year":"2012","course":"BSC"}, 
    {"studentId":"1001259101","firstName":"RAKESH","lastName":"DALAL","year":"2012","course":"BSC"} 
] 
+4

你嘗試過這麼遠嗎?這個網站在你嘗試一些東西並被卡住時幫助你很好。但是從頭開始編寫代碼是你自己的工作。 –

+0

這不是教程或代碼編寫服務。你應該能夠找到大量的教程來幫助你開始並在你有合法的代碼問題時回來 – charlietfl

+0

@Nira http://stackoverflow.com/help/how-to-ask – Gandhi

回答

0

迭代在陣列上,並在表中顯示它:

var jsonObject = [ 
    {studentId: "1001259101", firstName: "RAKESH", lastName: "DALAL", year: "2012", course: "BSC"}, 
    {studentId: "1001259101", firstName: "RAKESH", lastName: "DALAL", year: "2012", course: "BSC"}, 
    {studentId: "1001259101", firstName: "RAKESH", lastName: "DALAL", year: "2012", course: "BSC"} 
]; 

var output = "<table>"; 
for (var i = 0, len = jsonObject.length; i < len; i++) { 
    var line = jsonObject[i]; 
    output += "<tr>"; 
    output += "<td>" + line.studentId + "</td>"; 
    output += "<td>" + line.firstName + "</td>"; 
    output += "<td>" + line.lastName + "</td>"; 
    output += "<td>" + line.year + "</td>"; 
    output += "<td>" + line.course + "</td>"; 
    output += "</tr>"; 
} 
output += "</table>"; 

document.getElementById(...).innerHTML = output; 
0

那麼首先JSON的是(JavaScript對象符號)。相同的JS,對於對象表示法來說只是一點點不同的語法。

你需要以從其他文件接收JSON數據使用AJAX,只要看看:

var xhr = new XMLHttpRequest(); 
var url = "myJSON.json"; // your JSON text file 

xhr.onreadystatechange = function() { 
    if (xhr.readyState == 4 && xhr.status == 200) { 
     var myResponse = JSON.parse(xhr.responseText); 

     display(myResponse); // send array to function 
    } 
} 

xhr.open("GET", url, true); 
xhr.send(null); 

function display(arr) { 
    var myTable = "<table>"; // create a table variable 

    for (var i = 0; i < arr.length; i++) { // loop through array 
     myTable += "<tr>"; 
     myTable += "<td>" + arr[i].studentId + "</td>"; 
     myTable += "<td>" + arr[i].firstName + "</td>"; 
     myTable += "<td>" + arr[i].lastName + "</td>"; 
     myTable += "<td>" + arr[i].year + "</td>"; 
     myTable += "<td>" + arr[i].course + "</td>"; 
     myTable += "</tr>"; 
    } 

    myTable += "</table>"; 

    document.getElementById("myAwesomeTable").innerHTML = myTable; // display the final result in to html 
} 
  1. 使用Ajax爲了打開您的JSON的文本文件,它可以是.txt,以.json等
  2. 使用JSON.parse()來給你的JSON文本轉換爲數組
  3. 發送該陣列的功能
  4. 創建一個表,並持有可變一切都像一個文本
  5. 遍歷數組
  6. 顯示你的表中的HTML