使用jQuery从Ajax响应(Json)构build表行

可能的重复嵌套元素

我从服务器端Ajax响应(JSON),我试图dynamic创build表行,并将其附加到现有的表(ID: #records_table );

我试图执行可能重复的解决scheme,但失败了。

我的回复如下所示:

  "[{ "rank":"9", "content":"Alon", "UID":"5" }, { "rank":"6", "content":"Tala", "UID":"6" }]" 

要求的结果是这样的:

 <tr> <td>9</td> <td>Alon</td> <td>5</td> </tr> <tr> <td>6</td> <td>Tala</td> <td>5</td> </tr> 

我想在不parsingJson的情况下做一些事情,所以我试图做到以下几点,这当然是一场灾难:

  function responseHandler(response) { $(function() { $.each(response, function(i, item) { $('<tr>').html( $('td').text(item.rank), $('td').text(item.content), $('td').text(item.UID) ).appendTo('#records_table'); }); }); } 

从我的解决scheme中,我只得到了所有单元格中数字6的一行。 我究竟做错了什么?

10 Solutions collect form web for “使用jQuery从Ajax响应(Json)构build表行”

使用.append而不是.html

 var response = "[{ "rank":"9", "content":"Alon", "UID":"5" }, { "rank":"6", "content":"Tala", "UID":"6" }]"; // convert string to JSON response = $.parseJSON(response); $(function() { $.each(response, function(i, item) { var $tr = $('<tr>').append( $('<td>').text(item.rank), $('<td>').text(item.content), $('<td>').text(item.UID) ); //.appendTo('#records_table'); console.log($tr.wrap('<p>').html()); }); }); 

尝试这个:

 success: function (response) { var trHTML = ''; $.each(response, function (i, item) { trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>'; }); $('#records_table').append(trHTML); } 

与AJAX小提琴演示

这是来自hmkcode.com的完整答案

如果我们有这样的JSON数据

 // JSON Data var articles = [ { "title":"Title 1", "url":"URL 1", "categories":["jQuery"], "tags":["jquery","json","$.each"] }, { "title":"Title 2", "url":"URL 2", "categories":["Java"], "tags":["java","json","jquery"] } ]; 

而我们想在这个表结构中查看

 <table id="added-articles" class="table"> <tr> <th>Title</th> <th>Categories</th> <th>Tags</th> </tr> </table> 

下面的JS代码将填充为每个JSON元素创build一个行

 // 1. remove all existing rows $("tr:has(td)").remove(); // 2. get each article $.each(articles, function (index, article) { // 2.2 Create table column for categories var td_categories = $("<td/>"); // 2.3 get each category of this article $.each(article.categories, function (i, category) { var span = $("<span/>"); span.text(category); td_categories.append(span); }); // 2.4 Create table column for tags var td_tags = $("<td/>"); // 2.5 get each tag of this article $.each(article.tags, function (i, tag) { var span = $("<span/>"); span.text(tag); td_tags.append(span); }); // 2.6 Create a new row and append 3 columns (title+url, categories, tags) $("#added-articles").append($('<tr/>') .append($('<td/>').html("<a href='"+article.url+"'>"+article.title+"</a>")) .append(td_categories) .append(td_tags) ); }); 

试试像这样:

 $.each(response, function(i, item) { $('<tr>').html("<td>" + response[i].rank + "</td><td>" + response[i].content + "</td><td>" + response[i].UID + "</td>").appendTo('#records_table'); }); 

演示: http : //jsfiddle.net/R5bQG/

你不应该为每个单元格和行创buildjquery对象。 尝试这个:

 function responseHandler(response) { var c = []; $.each(response, function(i, item) { c.push("<tr><td>" + item.rank + "</td>"); c.push("<td>" + item.content + "</td>"); c.push("<td>" + item.UID + "</td></tr>"); }); $('#records_table').html(c.join("")); } 
 $.ajax({ type: 'GET', url: urlString , dataType: 'json', success: function (response) { var trHTML = ''; for(var f=0;f<response.length;f++) { trHTML += '<tr><td><strong>' + response[f]['app_action_name']+'</strong></td><td><span class="label label-success">'+response[f]['action_type'] +'</span></td><td>'+response[f]['points']+'</td></tr>'; } $('#result').html(trHTML); $( ".spin-grid" ).removeClass( "fa-spin" ); } }); 

我已经创build了这个JQuery函数

 /** * Draw a table from json array * @param {array} json_data_array Data array as JSON multi dimension array * @param {array} head_array Table Headings as an array (Array items must me correspond to JSON array) * @param {array} item_array JSON array's sub element list as an array * @param {string} destinaion_element '#id' or '.class': html output will be rendered to this element * @returns {string} HTML output will be rendered to 'destinaion_element' */ function draw_a_table_from_json(json_data_array, head_array, item_array, destinaion_element) { var table = '<table>'; //TH Loop table += '<tr>'; $.each(head_array, function (head_array_key, head_array_value) { table += '<th>' + head_array_value + '</th>'; }); table += '</tr>'; //TR loop $.each(json_data_array, function (key, value) { table += '<tr>'; //TD loop $.each(item_array, function (item_key, item_value) { table += '<td>' + value[item_value] + '</td>'; }); table += '</tr>'; }); table += '</table>'; $(destinaion_element).append(table); } ; 

jQuery.html将string或callback作为input,不知道你的例子是如何工作的…尝试像$('<tr>').append($('<td>' + item.rank + '</td>').append ... $('<tr/>')$('<td/>')

你可以这样做:

 <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script> $(function(){ $.ajax({ url: '<Insert your REST API which you want GET/POST/PUT/DELETE>', data: '<any parameters you want to send as the Request body or query string>', dataType: json, async: true, method: "GET" success: function(data){ //If the REST API returned a successful response it'll be stored in data, //just parse that field using jQuery and you're all set var tblSomething = '<thead> <tr> <td> Heading Col 1 </td> <td> Heading Col 2 </td> <td> Col 3 </td> </tr> </thead> <tbody>'; $.each(data, function(idx, obj){ //Outer .each loop is for traversing the JSON rows tblSomething += '<tr>'; //Inner .each loop is for traversing JSON columns $.each(obj, function(key, value){ tblSomething += '<td>' + value + '</td>'; }); tblSomething += '</tr>'; }); tblSomething += '</tbody>'; $('#tblSomething').html(tblSomething); }, error: function(jqXHR, textStatus, errorThrown){ alert('Hey, something went wrong because: ' + errorThrown); } }); }); </script> <table id = "tblSomething" class = "table table-hover"></table> 

我做了以下从Ajax获取JSON响应,并parsing而不使用parseJson:

 $.ajax({ dataType: 'json', <---- type: 'GET', url: 'get/allworldbankaccounts.json', data: $("body form:first").serialize(), 

如果你使用dataType作为文本,那么你需要$ .parseJSON(响应)

  • Django视图不使用模板返回json
  • 什么是JSONP?
  • 忽略Json.net中的空字段
  • REST与PHP中的RPC
  • 如何从Ruby on RailsfunctiontestingtestingJSON结果?
  • 正则expression式来validationJSON
  • Javascript Object push()函数
  • 如何将Joda DateTime与Jackson JSON处理器序列化?
  • 如何将console.log(object)的输出保存到文件中?
  • 我的传入Django请求中的JSON数据在哪里?
  • 有多lessJSON可以容纳的限制?