使用jQuery从AJAX响应(json)构建表行

时间:2013-07-18 12:52:59

标签: jquery json html-table

可能重复Nested elements

我从服务器端ajax响应(Json)得到,我正在尝试动态创建表行 并将它们附加到现有表格(ID:#records_table);

我尝试以可能重复的方式实施解决方案,但失败了。

我的回答如下:

    "[{
      "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>

我想在不解析Json的情况下做一些事情,所以我尝试做以下事情,这当然是一场灾难:

    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');

            });
        });


    }

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

12 个答案:

答案 0 :(得分:111)

使用.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());
    });
});

答案 1 :(得分:35)

试试这个(更新DEMO链接):

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);
    }

<强> Fiddle DEMO WITH AJAX

答案 2 :(得分:10)

以下是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元素

创建一行
// 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)
    ); 
});  

答案 3 :(得分:5)

试试这样:

$.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/

答案 4 :(得分:4)

您不应为每个单元格和行创建jquery对象。试试这个:

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(""));
}

答案 5 :(得分:4)

$.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" );
  }
});

答案 6 :(得分:2)

数据为 JSON

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

您可以使用 jQuery 迭代JSON并动态创建表:

num_rows = data.length;
num_cols = size_of_array(data[0]);

table_id = 'my_table';
table = $("<table id=" + table_id + "></table>");

header = $("<tr class='table_header'></tr>");
$.each(Object.keys(data[0]), function(ind_header, val_header) {
col = $("<td>" + val_header + "</td>");
header.append(col);
})
table.append(header);

$.each(data, function(ind_row, val) {
row = $("<tr></tr>");
$.each(val, function(ind_cell, val_cell) {
col = $("<td>" + val_cell + "</td>");
row.append(col);
})
table.append(row);
})

这是size_of_array函数:

function size_of_array(obj) {
    size = Object.keys(obj).length;
    return(size)
    };

如果需要,您还可以添加样式

$('.' + content['this_class']).children('canvas').remove();
$('.' + content['this_class']).append(table);
$('#' + table_id).css('width', '100%').css('border', '1px solid black').css('text-align', 'center').css('border-collapse', 'collapse');
$('#' + table_id + ' td').css('border', '1px solid black');

结果

enter image description here

或使用AZLE

Azle 中,您只需添加JSON数据即可创建表格,如下所示:

添加一个部分,其中包含一个div:

az.add_sections({
    "this_class": "my_sections",
    "sections": 1
})
az.add_html('my_sections', 1, {
    "html": "<div class='holdng_div'></div>"
})

enter image description here

创建一个绘制表的包装函数。在这里,我使用Azle的 add_layout fill_row 函数,以及一些循环和样式:

az.add_wrapped_function({
        "name": "draw_table",
        "function": function draw_table(data) {
            az.add_layout('holdng_div', 1, {
                "this_class": "my_table",
                "row_class": "my_table_rows",
                "cell_class": "my_table_cells",
                "number_of_rows": data.length,
                "number_of_columns": 5
            })
            data_ = data
            az.fill_row('my_table', 1, {
                "header": false,
                "cell_class": "my_table_cells",
                "text_class": "header_text",
                "row_number": 1,
                "array": Object.keys(data[0])
            })
            az.all_style_text('header_text', {
                "color": "yellow",
                "font-family": "Arial"
            })
            az.call_multiple({
                "iterations": data.length,
                "function": `
                    az.fill_row('my_table', 1, {
                        "header": true,
                        "cell_class": "my_table_cells",
                        "row_number": index + 1,
                        "array": [data_[index]['sepalLength'],data_[index]['sepalWidth'],data_[index]['petalLength'],data_[index]['petalWidth'],data_[index]['species']]
                        })
                        `
            })
            az.alternate_row_color('my_table', 1, 'whitesmoke', '#33AADE', 'black', 'black', true)
        }
    })

最后,调用返回数据的API (这里我使用Github上托管的Iris数据集)并将数据传递给我们的包装函数:

az.call_api({
        "url": "https://raw.githubusercontent.com/domoritz/maps/master/data/iris.json",
        "parameters": {},
        "done": "az.call_wrapped_function.draw_table(data)"
    })

结果

enter image description here

以下是GIST

以下是FIDDLE

答案 7 :(得分:1)

我已经创建了这个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);
}
;

答案 8 :(得分:1)

你可以这样做:

<!-- 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>

答案 9 :(得分:0)

jQuery.html将字符串或回调作为输入,不确定您的示例是如何工作的...尝试类似$('<tr>').append($('<td>' + item.rank + '</td>').append ...的内容 而且你对标签的确存在一定的问题。它应该是$('<tr/>')$('<td/>')

答案 10 :(得分:0)

我这样做是为了从Ajax获取JSON响应并在不使用parseJson的情况下进行解析:

        <!DOCTYPE html>
    <html>
    <head>
        <title></title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <link href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" rel="stylesheet"/>
    <link href="https://cdn.datatables.net/buttons/1.2.4/css/buttons.dataTables.min.css" rel="stylesheet"/>

    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.2.3/css/select.dataTables.min.css">


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.18/pdfmake.min.js"></script>

    <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.bootstrap.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.html5.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.print.js"></script>

    <script src="https://cdn.datatables.net/select/1.2.3/js/dataTables.select.min.js"></script>


    </head>
    <body>

    <table id="example" class="display" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th></th>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Office</th>
                    <th>Age</th>
                    <th>Salary</th>
                </tr>
            </thead>
            <tfoot>
                <tr>
                    <th></th>
                    <th>Name</th>
                    <th>Position</th>
                    <th>Office</th>
                    <th>Age</th>
                    <th>Salary</th>
                </tr>
            </tfoot>
            <tbody>
                <tr>
                    <td></td>
                    <td>Tiger Nixon</td>
                    <td>System Architect</td>
                    <td>Edinburgh</td>
                    <td>61</td>
                    <td>$320,800</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Garrett Winters</td>
                    <td>Accountant</td>
                    <td>Tokyo</td>
                    <td>63</td>
                    <td>$170,750</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Ashton Cox</td>
                    <td>Junior Technical Author</td>
                    <td>San Francisco</td>
                    <td>66</td>
                    <td>$86,000</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Cedric Kelly</td>
                    <td>Senior Javascript Developer</td>
                    <td>Edinburgh</td>
                    <td>22</td>
                    <td>$433,060</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Airi Satou</td>
                    <td>Accountant</td>
                    <td>Tokyo</td>
                    <td>33</td>
                    <td>$162,700</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Brielle Williamson</td>
                    <td>Integration Specialist</td>
                    <td>New York</td>
                    <td>61</td>
                    <td>$372,000</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Herrod Chandler</td>
                    <td>Sales Assistant</td>
                    <td>San Francisco</td>
                    <td>59</td>
                    <td>$137,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Rhona Davidson</td>
                    <td>Integration Specialist</td>
                    <td>Tokyo</td>
                    <td>55</td>
                    <td>$327,900</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Colleen Hurst</td>
                    <td>Javascript Developer</td>
                    <td>San Francisco</td>
                    <td>39</td>
                    <td>$205,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Sonya Frost</td>
                    <td>Software Engineer</td>
                    <td>Edinburgh</td>
                    <td>23</td>
                    <td>$103,600</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Jena Gaines</td>
                    <td>Office Manager</td>
                    <td>London</td>
                    <td>30</td>
                    <td>$90,560</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Quinn Flynn</td>
                    <td>Support Lead</td>
                    <td>Edinburgh</td>
                    <td>22</td>
                    <td>$342,000</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Charde Marshall</td>
                    <td>Regional Director</td>
                    <td>San Francisco</td>
                    <td>36</td>
                    <td>$470,600</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Haley Kennedy</td>
                    <td>Senior Marketing Designer</td>
                    <td>London</td>
                    <td>43</td>
                    <td>$313,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Tatyana Fitzpatrick</td>
                    <td>Regional Director</td>
                    <td>London</td>
                    <td>19</td>
                    <td>$385,750</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Michael Silva</td>
                    <td>Marketing Designer</td>
                    <td>London</td>
                    <td>66</td>
                    <td>$198,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Paul Byrd</td>
                    <td>Chief Financial Officer (CFO)</td>
                    <td>New York</td>
                    <td>64</td>
                    <td>$725,000</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Gloria Little</td>
                    <td>Systems Administrator</td>
                    <td>New York</td>
                    <td>59</td>
                    <td>$237,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Bradley Greer</td>
                    <td>Software Engineer</td>
                    <td>London</td>
                    <td>41</td>
                    <td>$132,000</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Dai Rios</td>
                    <td>Personnel Lead</td>
                    <td>Edinburgh</td>
                    <td>35</td>
                    <td>$217,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Jenette Caldwell</td>
                    <td>Development Lead</td>
                    <td>New York</td>
                    <td>30</td>
                    <td>$345,000</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Yuri Berry</td>
                    <td>Chief Marketing Officer (CMO)</td>
                    <td>New York</td>
                    <td>40</td>
                    <td>$675,000</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Caesar Vance</td>
                    <td>Pre-Sales Support</td>
                    <td>New York</td>
                    <td>21</td>
                    <td>$106,450</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Doris Wilder</td>
                    <td>Sales Assistant</td>
                    <td>Sidney</td>
                    <td>23</td>
                    <td>$85,600</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Angelica Ramos</td>
                    <td>Chief Executive Officer (CEO)</td>
                    <td>London</td>
                    <td>47</td>
                    <td>$1,200,000</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Gavin Joyce</td>
                    <td>Developer</td>
                    <td>Edinburgh</td>
                    <td>42</td>
                    <td>$92,575</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Jennifer Chang</td>
                    <td>Regional Director</td>
                    <td>Singapore</td>
                    <td>28</td>
                    <td>$357,650</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Brenden Wagner</td>
                    <td>Software Engineer</td>
                    <td>San Francisco</td>
                    <td>28</td>
                    <td>$206,850</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Fiona Green</td>
                    <td>Chief Operating Officer (COO)</td>
                    <td>San Francisco</td>
                    <td>48</td>
                    <td>$850,000</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Shou Itou</td>
                    <td>Regional Marketing</td>
                    <td>Tokyo</td>
                    <td>20</td>
                    <td>$163,000</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Michelle House</td>
                    <td>Integration Specialist</td>
                    <td>Sidney</td>
                    <td>37</td>
                    <td>$95,400</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Suki Burks</td>
                    <td>Developer</td>
                    <td>London</td>
                    <td>53</td>
                    <td>$114,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Prescott Bartlett</td>
                    <td>Technical Author</td>
                    <td>London</td>
                    <td>27</td>
                    <td>$145,000</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Gavin Cortez</td>
                    <td>Team Leader</td>
                    <td>San Francisco</td>
                    <td>22</td>
                    <td>$235,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Martena Mccray</td>
                    <td>Post-Sales support</td>
                    <td>Edinburgh</td>
                    <td>46</td>
                    <td>$324,050</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Unity Butler</td>
                    <td>Marketing Designer</td>
                    <td>San Francisco</td>
                    <td>47</td>
                    <td>$85,675</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Howard Hatfield</td>
                    <td>Office Manager</td>
                    <td>San Francisco</td>
                    <td>51</td>
                    <td>$164,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Hope Fuentes</td>
                    <td>Secretary</td>
                    <td>San Francisco</td>
                    <td>41</td>
                    <td>$109,850</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Vivian Harrell</td>
                    <td>Financial Controller</td>
                    <td>San Francisco</td>
                    <td>62</td>
                    <td>$452,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Timothy Mooney</td>
                    <td>Office Manager</td>
                    <td>London</td>
                    <td>37</td>
                    <td>$136,200</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Jackson Bradshaw</td>
                    <td>Director</td>
                    <td>New York</td>
                    <td>65</td>
                    <td>$645,750</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Olivia Liang</td>
                    <td>Support Engineer</td>
                    <td>Singapore</td>
                    <td>64</td>
                    <td>$234,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Bruno Nash</td>
                    <td>Software Engineer</td>
                    <td>London</td>
                    <td>38</td>
                    <td>$163,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Sakura Yamamoto</td>
                    <td>Support Engineer</td>
                    <td>Tokyo</td>
                    <td>37</td>
                    <td>$139,575</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Thor Walton</td>
                    <td>Developer</td>
                    <td>New York</td>
                    <td>61</td>
                    <td>$98,540</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Finn Camacho</td>
                    <td>Support Engineer</td>
                    <td>San Francisco</td>
                    <td>47</td>
                    <td>$87,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Serge Baldwin</td>
                    <td>Data Coordinator</td>
                    <td>Singapore</td>
                    <td>64</td>
                    <td>$138,575</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Zenaida Frank</td>
                    <td>Software Engineer</td>
                    <td>New York</td>
                    <td>63</td>
                    <td>$125,250</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Zorita Serrano</td>
                    <td>Software Engineer</td>
                    <td>San Francisco</td>
                    <td>56</td>
                    <td>$115,000</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Jennifer Acosta</td>
                    <td>Junior Javascript Developer</td>
                    <td>Edinburgh</td>
                    <td>43</td>
                    <td>$75,650</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Cara Stevens</td>
                    <td>Sales Assistant</td>
                    <td>New York</td>
                    <td>46</td>
                    <td>$145,600</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Hermione Butler</td>
                    <td>Regional Director</td>
                    <td>London</td>
                    <td>47</td>
                    <td>$356,250</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Lael Greer</td>
                    <td>Systems Administrator</td>
                    <td>London</td>
                    <td>21</td>
                    <td>$103,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Jonas Alexander</td>
                    <td>Developer</td>
                    <td>San Francisco</td>
                    <td>30</td>
                    <td>$86,500</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Shad Decker</td>
                    <td>Regional Director</td>
                    <td>Edinburgh</td>
                    <td>51</td>
                    <td>$183,000</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Michael Bruce</td>
                    <td>Javascript Developer</td>
                    <td>Singapore</td>
                    <td>29</td>
                    <td>$183,000</td>
                </tr>
                <tr>
                    <td></td>
                    <td>Donna Snider</td>
                    <td>Customer Support</td>
                    <td>New York</td>
                    <td>27</td>
                    <td>$112,000</td>
                </tr>
            </tbody>
        </table>


    <script>

    $(document).ready(function() {
        var table = $('#example').DataTable( {
            dom: 'Bfrtip',
            buttons: [
                'copy', 'csv', 'pdf', 'print',
                {
                    extend: 'print',
                    text: 'Print selected',
                    exportOptions: {
                        modifier: {
                            selected: true
                        }
                    }
                },
                {
                    extend: 'csv',
                    text: 'CSV selected',
                    exportOptions: {
                        modifier: {
                            selected: true
                        }
                    }
                }                    

            ],        
            columnDefs: [ {
                orderable: false,
                className: 'select-checkbox',
                targets:   0,
                checkboxes : {
                    selectRow : true
                }
            } ],
            select: {
                style:    'multi',
                selector: 'td:first-child'
            },
            order: [[ 1, 'asc' ]]

        } );



    } );

    </script>

    </body>
    </html>

如果您使用dataType作为Text,那么您需要$ .parseJSON(响应)

答案 11 :(得分:0)

这是我从项目中复制的工作示例。

 function fetchAllReceipts(documentShareId) {

        console.log('http call: ' + uri + "/" + documentShareId)
        $.ajax({
            url: uri + "/" + documentShareId,
            type: "GET",
            contentType: "application/json;",
            cache: false,
            success: function (receipts) {
                //console.log(receipts);

                $(receipts).each(function (index, item) {
                    console.log(item);
                    //console.log(receipts[index]);

                    $('#receipts tbody').append(
                        '<tr><td>' + item.Firstname + ' ' + item.Lastname +
                        '</td><td>' + item.TransactionId +
                        '</td><td>' + item.Amount +
                        '</td><td>' + item.Status + 
                        '</td></tr>'
                    )

                });


            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest);
                console.log(textStatus);
                console.log(errorThrown);

            }

        });
    }
    
    
    // Sample json data coming from server
    
    var data =     [
    0: {Id: "7a4c411e-9a84-45eb-9c1b-2ec502697a4d", DocumentId: "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6", DocumentShareId: "d99803ce-31d9-48a4-9d70-f99bf927a208", Firstname: "Test1", Lastname: "Test1", }
    1: {Id: "7a4c411e-9a84-45eb-9c1b-2ec502697a4d", DocumentId: "e6eb6f85-3f44-4bba-8cb0-5f2f97da17f6", DocumentShareId: "d99803ce-31d9-48a4-9d70-f99bf927a208", Firstname: "Test 2", Lastname: "Test2", }
];
  <button type="button" class="btn btn-primary" onclick='fetchAllReceipts("@share.Id")'>
                                        RECEIPTS
                                    </button>
 
 <div id="receipts" style="display:contents">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Transaction</th>
                            <th>Amount</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
         </div>