How to consume ajax returned json data in DataTabl

2019-08-02 02:38发布

I want to consume ajax returned data in my JQuery DataTables. I have created loop to view every row and also need to add a view button for them. I pass all data to JQuery DataTables. I cannot understand how to do that.

This is my ajax request

  <script>
        $(document).ready(function () {
            $("#searchArea").show();
            var uID = $("#userName").val();

            var tableProduct = $('#dataTbl').DataTable({
                "bSort": false
                , "oLanguage": {"sZeroRecords": "", "sEmptyTable": ""}
            });
            $.ajax({
                type: 'GET',
                url: '${pageContext.request.contextPath}/restservice/viewApplication/' + uID,
                success: function (result) {
                    var jString = JSON.stringify(result);
                    var jdata = JSON.parse(jString);

                    for (var x = 0; x < jdata.length; x++) {

                        var td1 = jdata[x].snumber;
                        var td2 = jdata[x].date;
                        var td3 = jdata[x].slsNo + " in " + jdata[x].slsiUnit;
                        var td4 = jdata[x].productDesc;
                        var td5 = jdata[x].status;
                        var td6 = "view btn1";
                        var td7 = "view btn2";
                        var td8 = "view btn3";
                        tableProduct.row.add([td1, td2, td3, td4, td5, td6, td7, td8]).draw(true);
                    }
                }
            });

        });
    </script>

I want to add this code for every row. How can I do that ?

 <form method="post" action="${pageContext.request.contextPath}/viewApplication" target="_blank">
     <input type="hidden" name="snumber" value="jdata[x].snumber"/>
     <input type="submit" class="btn btn-primary btn-block" value="View" />
     <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
 </form>

1条回答
对你真心纯属浪费
2楼-- · 2019-08-02 02:59

Consuming Ajax data in DataTables

There is already a handy feature in DataTables to fetch data from ajax and consume them as you configure your table. Just use the ajax option and tell about the data source you want to consume

$('#dataList').DataTable({
    ajax: {
            url: 'url',
            type: 'GET',
            dataSrc: ''
    }
}

See this documentation for complete guideline.

Note: here passing dataSrc option as empty tells dataTable to expect an array rather than objects from ajax response

Following is a example that depicts a senario where datatable is configured to consume a api response. For demonastration purpose I used a public dummy api service that returned an json array. See this dummy api response.

$(function() {
  var columnArray = [{
      title: "Photo ID",
      data: "id",
      targets: 0
    },
    {
      title: "Photo Title",
      data: "title",
      targets: 1
    }
  ];

  $('#dataList').DataTable({
    ajax: {
      url: 'https://jsonplaceholder.typicode.com/photos',
      type: 'GET',
      dataSrc: ''
    },
    bBootstrapLayout: true,
    columns: columnArray,
    columnDefs: [{
      render: function(data, type, row) {
        return data + ' (' + row['albumId'] + ')';
      },
      targets: 0
    }, {
      render: function(data, type, row) {
        var html = '<button>view</button>';

        return html;
      },
      targets: 2
    }]
  });
});

  
<head>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
  <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
  <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />

  <head>

    <body>
      <br>
      <br>
      <div class="row">
        <div class="col-lg-1"></div>
        <div class="col-lg-6">
          <div>
            <table id="dataList" class="table" data-page-length="1" cellspacing="0" width="100%" />
          </div>
        </div>
      </div>
    </body>

Having Custom button or form in row

In your datatable you can configure each column rendering logic. Like the case you are dealing, you want separate columns of button behave as form submission. You should tell this in columnDefs option as passing an array of definations.

In the code snippet above I also showed how you can achive that. In that example I added 3rd column (target: 2) by defining its rendering logic. In render callback you can return html that should be placed in that column. I only added <button>view</button> but as you see you can return any html like forms with input fields and buttons and whats not. render option takes a function that is provided with data, type, row parameters. Hence you can exploit these data for rendering your column html or any logic you what. Thats a lot of flexibility, isn't it ?

You will find a complementary guildline from this columnDefs documentation.

查看更多
登录 后发表回答