简体   繁体   English

如何用XHR响应填充jQuery DataTable

[英]How to populate a jQuery DataTable with an XHR response

I've seen many questions about this but none of the answers have gotten me close enough to solve my problem. 我已经看到了许多与此有关的问题,但是没有一个答案使我足够接近以解决我的问题。 Hopefully it's a simple one for someone out there. 希望它对那里的某个人来说很简单。 I am trying to use an XHR response to populate a DataTable. 我正在尝试使用XHR响应来填充DataTable。 The request to the Java servlet is executed by a button click. 单击按钮即可执行对Java servlet的请求。 The request looks like this: 该请求看起来像这样:

function callFileSearchServlet(){
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "http://localhost:8080/FileSearch-1/FileSearch?selectedDataSource=foo&startDate=20180101&endDate=20180102", true );
  xhr.setRequestHeader("Content-type", "application/json");
  xhr.send(null);
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        theResponse = this.responseText;
        editedJsonText = theResponse.substring(8, theResponse.length-1);
        displaySearchResults();
    }
}    

For the sake of this post I hard coded the URL parameters that the servlet is expecting to receive. 为了这篇文章,我对servlet希望接收的URL参数进行了硬编码。 The servlet looks at the file system and writes metadata about the files to a JSON. Servlet查看文件系统,并将关于文件的元数据写入JSON。 The response technically includes the following text at the beginning 技术上,回复开头应包含以下文本

{"data":

but I'm not sure under what conditions it should actually be there so after trimming it, the response looks like this: 但是我不确定它实际上应该在什么条件下出现,因此在修剪之后,响应看起来像这样:

[{"date":"20180101","status":"Incomplete","total_files":66,"total_size":38014958},{"date":"20180102","status":"Complete","total_files":72,"total_size":55471119}]

The trouble is I can't just assign the response to a variable and use it to populate my DataTable. 问题是我不能仅仅将响应分配给变量,然后使用它来填充我的DataTable。 That approach worked when I used static data in my JavaScript file. 当我在JavaScript文件中使用静态数据时,这种方法有效。 I assigned the static data to a global JavaScript variable (myData) and used that variable as the data source in my DataTable. 我将静态数据分配给全局JavaScript变量(myData),并将该变量用作DataTable中的数据源。 Like this: $(document).ready(function () { var table = $('#search_results').DataTable({ "data": myData, "columns": [ { "className": "details-control", "orderable": "false", "data": "null", "defaultContent": '', "render": function () { return '<i class="fa fa-plus-square" aria-hidden="true"></i>'; }, "width":"15px" }, { "render": function () { return '<input type="checkbox" id="chkbx1" name="flightDirPaths" value="theValue1">'; } }, { "data": "date" }, { "data": "status" }, { "data": "total_files" }, { "data": "total_size" } ], "order": [[1, 'asc']] }); 像这样: $(document).ready(function () { var table = $('#search_results').DataTable({ "data": myData, "columns": [ { "className": "details-control", "orderable": "false", "data": "null", "defaultContent": '', "render": function () { return '<i class="fa fa-plus-square" aria-hidden="true"></i>'; }, "width":"15px" }, { "render": function () { return '<input type="checkbox" id="chkbx1" name="flightDirPaths" value="theValue1">'; } }, { "data": "date" }, { "data": "status" }, { "data": "total_files" }, { "data": "total_size" } ], "order": [[1, 'asc']] });

If I replace myData with the actual data, as it is formatted above, the table displays correctly. 如果我将myData替换为上面格式设置的实际数据,该表将正确显示。 So I know the format is good. 所以我知道格式很好。 So now I have the XHR response and I don't know how to make my DataTable use it. 因此,现在我有了XHR响应,而且我不知道如何使DataTable使用它。 I've looked at most of the documentation and a lot of forums but haven't seen how to do this. 我看了大部分文档和许多论坛,但还没有看到如何做。 Can it be done? 能做到吗 I get the feeling I have to use an AJAX request, which in spite of all the documentation I've read, I still don't really understand. 我觉得我必须使用AJAX请求,尽管我已经阅读了所有文档,但我仍然不太了解。 More specifically, the documentation here https://datatables.net/reference/option/ajax states the following: 更具体地说, https: //datatables.net/reference/option/ajax此处的文档规定了以下内容:

The ajax property has three different modes of operation, depending on how it is defined. ajax属性具有三种不同的操作模式,具体取决于其定义方式。 These are: string - Set the URL from where the data should be loaded from. 它们是:字符串-设置从中加载数据的URL。 object - Define properties for jQuery.ajax. 对象-定义jQuery.ajax的属性。 function - Custom data get function 功能-自定义数据获取功能

Is the "URL mode" supposed to be used when the data is written to a file somewhere? 将数据写入某个位置的文件时,是否应该使用“ URL模式”? Writing data to file so it can be ingested by a DataTable seems like an extra step compared to passing in the data directly from the servlet. 与直接从servlet传递数据相比,将数据写到文件以便可以被DataTable吸收似乎是一个额外的步骤。 Maybe I'm being myopic about it because I don't have much experience with this. 也许我对此很近视,因为我对此没有太多经验。 I've noticed that the vast majority of AJAX based solutions on Stackoverflow include the URL mode but my servlet isn't writing data to file, nor do I want it to. 我注意到,Stackoverflow上的绝大多数基于AJAX的解决方案都包括URL模式,但是我的servlet并没有将数据写入文件,也不想这样做。 I'm guessing the "function mode" is what I need to use. 我猜想我需要使用“功能模式”。 Can anyone confirm that? 谁能确认? If that's not the best solution does anyone know how I should do this? 如果那不是最好的解决方案,那么有人知道我应该怎么做吗? The documentation states that the function mode requires three parameters (data, callback, and settings), like this: 文档指出功能模式需要三个参数(数据,回调和设置),如下所示:

$('#example').dataTable({"ajax": function (data, callback,settings){callback(JSON.parse( localStorage.getItem('dataTablesData')));}}); 

I understand the parameters conceptually but there isn't much in the way of how to actually create each one. 我从概念上了解这些参数,但是如何实际创建每个参数没有太多方法。 For example, do I assign all of my servlet parameters (selectedDataSource, startDate, endDate) to a variable called "data?" 例如,我是否将所有servlet参数(selectedDataSource,startDate,endDate)分配给一个名为“ data”的变量? If so, what does that actually look like syntactically and exactly where in my JavaScript file do I create it? 如果是这样,那么在语法上实际上看起来是什么,以及在JavaScript文件中的确切位置创建它呢? The fine details of this process escape me. 这个过程的细节让我无所适从。 Perhaps there is some assumed knowledge that I don't have. 也许有些假定的知识我没有。 Any help is appreciated. 任何帮助表示赞赏。

I figured out a solution. 我想出了一个解决方案。 I didn't have to use the function mode. 我不必使用功能模式。 I just used an AJAX call inside the DataTable initialization instead of the XHR request outside of the table initialization. 我只是在DataTable初始化内部使用了AJAX调用,而不是在表初始化外部使用了XHR请求。 The URL value in the AJAX call is the URL of my servlet. AJAX调用中的URL值是我的servlet的URL。 So I deleted the XHR request, created an AJAX request in the table initialization, and moved it all into the button click function so when the user clicks the button the table appears with data returned from the servlet. 因此,我删除了XHR请求,在表初始化中创建了一个AJAX请求,并将其全部移到了按钮单击功能中,因此,当用户单击按钮时,该表将显示从Servlet返回的数据。 I posted new code above. 我在上面发布了新代码。 This site helped. 这个网站帮了忙。 https://datatables.net/forums/discussion/45615/how-to-load-table-from-ajax-request https://datatables.net/forums/discussion/45615/how-to-load-table-from-ajax-request

Here's my new code that works properly. 这是我的新代码,可以正常工作。 The difference between my old code and the code below is between the lines that start with "var table =..." and ""columns":..." 我的旧代码和下面的代码之间的区别是,以“ var table = ...”和““ columns”:...”开头的行之间

$(document).ready(function () {
    var table = $('#search_results').DataTable({
        "ajax": {
            url: "http://localhost:8080/FileSearch-1/FileSearch?selectedSources=foo&startDate=20180101&endDate=20180102",
            method: "GET",
            xhrFields: {
                withCredentials: true
            }
        },
        "columns": [
            {
            "className": "details-control",
            "orderable": "false",
            "data": "null",
            "defaultContent": '',
            "render": function () {
                return '<i class="fa fa-plus-square" aria-hidden="true"></i>';
            },
            "width":"15px"
            },
            { "render": function () {
                return '<input type="checkbox" id="chkbx1" name="flightDirPaths" value="theValue1">';
                }
            }, 
            { "data": "date" },
            { "data": "status" },
            { "data": "total_files" },
            { "data": "total_size" }
        ],
        "order": [[1, 'asc']]
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM