weixin_33749131 2018-01-24 10:56 采纳率: 0%
浏览 69

DataTables AJAX动态网址

I want to create a general function to initialise all my ajax DataTables.

I need to be able to identify the table that is requesting data so my server-side script knows which data to send back.

I thought I'd simply be able to attach the table ID to the ajax URL like so:

$(document).ready(function() {
    $('#example').DataTable({
        "ajax": {
            "url": "www.example.com/load-" + this.id + ".php"
        }
    });
});

I thought the URL would resolve to "www.example.com/load-example.php" but it didn't work as this.id is undefined (as is $(this).attr('id')) so I thought maybe I could use a single server-side script and pass in an extra $_GET parameter like so:

$(document).ready(function() {
    $('#example').DataTable({
        "ajax": {
            url: "www.example.com/load-table.php",
            data: function ( d ) {
                d.experiment = this.id;
            }
        }
    });
});

This also failed for the same reason.

Is it possible to get the table ID when retrieving data this way?

  • 写回答

1条回答 默认 最新

  • weixin_33724059 2018-01-24 12:37
    关注

    I've found a solution that works but if someone has a better way, please post your solution here.

    This solution binds to any table that has the class 'data-table'.

    $(document).ready(function() {
        $('.data-table').each(function(index) {
            var table = this.id;
            $(this).DataTable({
                "ajax": {
                    "url": "www.example.com/load-" + table + ".php"
                }
            });
        });
    });
    
    评论

报告相同问题?