Подтвердить что ты не робот

Datatables: как поймать ошибку при использовании пользовательской функции ajax?

При использовании datatables Мне нужно использовать пользовательскую ajax-функцию.

Канонический пример, найденный здесь, выглядит следующим образом:

$('#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 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 an actual error?
    callback(err);
  }
} );

Тем не менее, я не вижу способа сообщить datatables, что произошла ошибка ajax.

Как это сделать?

4b9b3361

Ответ 1

Попробовав несколько разных методов, я думаю, что лучше всего будет вызвать функцию callback с вашими данными с успехом и вызвать callback с пустыми данными об ошибке. Если есть ошибка, вы можете установить текст строки .dataTables_empty в текст сообщения об ошибке, чтобы он отображался в таблице. Вот как это будет работать, и как выглядит код:

Важное примечание. Обязательно установите .dataTables_empty текст после, вы вызываете обратный вызов, потому что обратный вызов вернет его (что действительно приятно, потому что тогда вы не должны reset сами при каждой загрузке данных)

$('#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="#" onclick="location.href='https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css'; return false;" />
<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>