javascript - 数据表:使用自定义ajax函数时如何捕获错误?

标签 javascript jquery ajax datatables

在使用 datatables 时我需要使用自定义的 ajax 函数。

找到的典型示例 here如下:

$('#example').dataTable( {
  "ajax": function (data, callback, settings) {
    //some async processing happening here
    //In the end call the callback. 
    //However, this callback only accepts a success state
    // instead of the usual cb(err, resp) signature. 
    //This raises the question how to let Datatables know there's an error.
    const err = new Error("some contrived error");


    //This doesn't work, datatables doesn't signal an actual error
    //which can be surfaced to the client. Instead it complains
    //the response doesn't have a 'data'-object which it needs
    //to correctly create the table. In other words, datatables
    //thinks that the passed err-object is an actual correct response. 

    //Question: so how to actually let datatables know there's an actual error?
    callback(err);
  }
} );

但是,我看不到让数据表知道发生了 ajax 错误的方法。

如何做到这一点?

最佳答案

在尝试了几种不同的方法之后,我认为最好的办法是在成功时用数据调用 callback 函数,在成功时用空数据调用 callback失败。如果有错误,您可以将 .dataTables_empty 行的文本设置为您的错误消息的文本,这样它就会显示在表格中。下面是它的工作原理,以及代码的样子:

重要说明 - 确保在调用回调后设置.dataTables_empty文本,因为回调会将其设置回去(这这实际上很好,因为这样您就不必在每次数据加载时自己重置它)

$('#example').dataTable( {
  "columns": [
    {"data": "col1"},
    {"data": "col2"},
    {"data": "col3"},
  ],
  "ajax": function (data, callback, settings) {
    // simulate ajax call with successful data retrieval
    var myAjaxCall = new Promise(function (resolve, reject) {
      $(".dataTables_empty").text("Loading...");
      setTimeout(function () {
        // `callback()` expects an object with a data property whose value is either 
        // an array of arrays or an array of objects. Must be in this format
        // or you get errors.
        var ajaxData = {"data": [
          {"col1": "1.1", "col2": "1.2", "col3": "1.3"},
          {"col1": "2.1", "col2": "2.2", "col3": "2.3"},
          {"col1": "3.1", "col2": "3.2", "col3": "3.3"}
        ]};
        resolve(ajaxData);
      }, 1500);
    });
    
    myAjaxCall.then(function resolveCallback(data) {
      // render data returned from ajax call
      callback(data);
    }, function rejectCallback(err) {
      callback({data: []});
      $(".dataTables_empty").text(err); 
    });
  }
});

$('#example2').dataTable( {
  "columns": [
    {"data": "col1"},
    {"data": "col2"},
    {"data": "col3"},
  ],
  "ajax": function (data, callback, settings) {
    // simulate unsuccessful ajax call
    var myAjaxCall2 = new Promise(function (resolve, reject) {
      $(".dataTables_empty").text("Loading...");
      setTimeout(function () {
        // reject promise with error message
        reject("Something went terribly wrong!");
      }, 1500);
    });
    
    myAjaxCall2.then(function resolveCallback(data) {
      callback(data);
    }, function rejectCallback(err) {
      // render table with no results
      callback({data: []});
      // set dataTables empty message text to error message
      $(".dataTables_empty").text(err); 
    });
  }
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" />
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<h1>Success</h1>
<table id="example">
  <thead>
    <tr>
      <th>Col 1</th>
      <th>Col 2</th>
      <th>Col 3</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
<h1>Error</h1>
<table id="example2">
  <thead>
    <tr>
      <th>Col 1</th>
      <th>Col 2</th>
      <th>Col 3</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

关于javascript - 数据表:使用自定义ajax函数时如何捕获错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44776515/

相关文章:

jquery - 如何在刷新后或加载不同页面时保持颜色变化?

javascript - 使用 PHP CodeIgniter、JQuery、AJAX 验证数据库中是否已存在用户名

javascript - 如何在我的代码中使用 AJAX 和 JSON

javascript - 从 XMLHttpRequest 中删除 HTTP header

javascript - 将 Jasmine 单元测试与 100 多个相同类型的测试一起使用

javascript - 更改部分文本的颜色 css 或 javascript

javascript - 表单 HTML 未更新。

ajax - 进行多个 ajax 回调时保持请求的顺序

javascript - 将钩子(Hook)作为 Prop 传递

javascript - Vuejs 和 vue-socketio : how to pass socket instance to components