2016-12-29 81 views
0

如何在該json值上生成表格。裏面的ajax函數的數據是在控制檯中打印的,而且在jsp中,但在其外側值是未定義的錯誤是什麼?如何在jsp頁面內使用ajax函數的json值?

<head> 
<title>Spring MVC Ajax Demo</title> 
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
<script type="text/javascript"> 
function doAjax() { 
    var samp; 
    $.ajax({ 
     url : '/RoomController/ViewMember', 
     type : 'GET', 
     success : function(data) { 
      samp=data; 
      console.log(samp[0].memberName); 
      $('#json').html(samp[3].memberName); 
     } 
    }); 
    document.getElementById("memberList").value=samp; 
} 
</script> 
</head> 
<body> 
<button id="demo" onclick="doAjax()" title="Button">Get the 
    time!</button> 
<div id="time"> 
    <label id="json"></label> 
    <input type="hidden" id="memberList" name="memberList"> 
    <table> 
     <c:forEach items="${memberList}" var="firstname"> 
      <tr> 
       <td>${firstname.memberName}</td> 
      </tr> 
     </c:forEach> 

    </table> 

</div> 

回答

0

試試這個。注意:此用了jQuery

的Javascript:

var myList = [{"name" : "abc", "age" : 50}, 
      {"age" : "25", "hobby" : "swimming"}, 
      {"name" : "xyz", "hobby" : "programming"}]; 

// Builds the HTML Table out of myList. 
function buildHtmlTable(selector) { 
    var columns = addAllColumnHeaders(myList, selector); 

for (var i = 0 ; i < myList.length ; i++) { 
    var row$ = $('<tr/>'); 
    for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) { 
     var cellValue = myList[i][columns[colIndex]]; 

     if (cellValue == null) { cellValue = ""; } 

     row$.append($('<td/>').html(cellValue)); 
    } 
    $(selector).append(row$); 
} 
} 

// Adds a header row to the table and returns the set of columns. 
// Need to do union of keys from all records as some records may not contain 
// all records 

function addAllColumnHeaders(myList, selector) 

{ 
    var columnSet = []; 
var headerTr$ = $('<tr/>'); 

for (var i = 0 ; i < myList.length ; i++) { 
    var rowHash = myList[i]; 
    for (var key in rowHash) { 
     if ($.inArray(key, columnSet) == -1){ 
      columnSet.push(key); 
      headerTr$.append($('<th/>').html(key)); 
     } 
    } 
} 
$(selector).append(headerTr$); 

return columnSet; 
}​ 

HTML:

<body onLoad="buildHtmlTable('#excelDataTable')"> 
<table id="excelDataTable" border="1"> 
    </table> 
</body>​ 

要調用表,嘗試根據你的代碼它

table.on('xhr', function() { 
    var ajaxJson = table.ajax.json(); 
    alert(ajaxJson.data.length + ' row(s) were loaded'); 
}); 

變化。

+0

沒關係,但是如何獲得ajax函數外部的'samp'值。只要我把'console.log(samp [0] .memberName);' ajax的外側意味着它是未定義的。 – Manihtraa

+0

@Manihtraa我編輯了我的答案。再試一次 – Farid

相關問題