JQuery Ajax動態加載Table數據

我們在jsp定義一個select和一個table,要求實現根據select的選值,動態加載table數據。

<select id="type" name="type" onchange="reloadTable(this)"></select>
 <table id="import-table" class="table table-striped table-bordered table-hover" width="100%"></table>

table第一次加載數據的function定義如下:

function loadData() {
    var c = '<label><input type="checkbox" id="checkbox1" class="ace" onchange="javascrpt:selectAll(this);"/><span class="lbl"></span></label>';
    $('#import-table').DataTable({
        ajax: {
            url: '<%=request.getContextPath()%>' + "../../../hot/getByCode.action?code=APP",
            type: "post",
            dataType: "json",
            data: {}
        },
        "scrollCollapse": true,
        ordering: false,
        visible: true,
        api: true,
        serverSide: true,
        columns: [{
            "data": "id",
            "class": "center",
            "width": "80px",
            "name": "importId",
            orderable: false,
            "title": c,
            "render": function(a, b, c, d) {
                return getColumnReturnStr("checkbox", c.id, "importId")
            }
        },
        {
            "data": "name",
            "title": "名稱"
        },
        ],
        "dom": "<'row'<'col-sm-6'l><'col-sm-6'f>r>t<'row'<'col-sm-6'i><'col-sm-6'p>>",
        initComplete: function() {}
    });
}

接着需要考慮,如何在select選值改變的時候,更新table中ajax的url地址,實現table的reload

function reloadTable(){ 
   var code = $("#type option:selected").val();

  $('#import-table').DataTable()
  .ajax.url(  
        '<%=request.getContextPath()%>'+"../../../hot/getByCode.action?code="+ code
  ).load();

}

這樣我們便可以通過改變select選值,動態加載table數據。
通過$(‘#import-table’).DataTable().ajax.url().load();方法實現。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章