Прерывистая ошибка «Не удается повторно инициализировать таблицу данных» - PullRequest
0 голосов
/ 19 октября 2019

Я делаю проект с DataTable (https://datatables.net), и у меня возникает довольно странная проблема.

Иногда, когда я загружаю страницу, все работает на 100%, а иногда - когдазагрузите страницу, я получаю эту ошибку от DataTables во всплывающем окне:

DataTables warning: table id=resdatatable - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3

Как я уже сказал, нет никакого точного пожарного способа вызвать это. Если я нажму на обновление, иногда это будет работать, иногда это даст мнеэта ошибка.

Я не пытаюсь повторно инициализировать DataTable, поэтому я немного смущен тем, почему это происходит. Я проверил ссылку в описании, но не понимаю, как это исправить.

Вот мой код:

    let statusList = getStatusList();

function getRes(callback) { // ADDED CALLBACK
    let city = document.getElementById("cityselect").value;
    $.ajax({
        type: 'get',
        url: 'getreservationstable.php?city='+city,
        dataType: 'json',
        cache: false,
        success: callback  // USED CALLBACK
    });
}

function changeCity()
{
    $('#resdatatable').DataTable().ajax.reload();
}

getRes(function (result) { // APPLIED CALLBACK
  $('#resdatatable').DataTable({
     data: result,             // YOUR RESULT
      columns: [
        { data: 'id', title: 'ID' },
        { data: 'bookingdatetime', title: 'Booking Date' },
        { data: 'name', title: 'Name' },
        { data: 'class', title: 'Class' },
        { data: 'pickupdatetime', title: 'Pick up' },
        { data: 'duration', title: 'Duration' },
        { data: 'dropdatetime', title: 'Drop off' },
        { data: 'age', title: 'Age' },
        { data: 'coverage', title: 'Coverage' },
        { data: 'quote', title: 'Quote' },
        {
          data: 'status',
          title: 'Status',
          render: function(data, type, row) {
            let isKnown = statusList.filter(function(k) { return k.id === data; }).length > 0;
            if (isKnown) {
              return $('<select id ="resstatus'  + row.id + '" onchange="changeResStatus(' + row.id + ')">', {
                id: 'resstatus-' + row.id, // custom id
                value: data
              }).append(statusList.map(function(knownStatus) {
                let $option = $('<option>', {
                  text: knownStatus.text,
                  value: knownStatus.id
                });
                if (row.status === knownStatus.id) {
                  $option.attr('selected', 'selected');
                }
                return $option;
              })).on('change', function() {
                changeresstatus(row.id); // Call change with row ID
              }).prop('outerHTML');
            } else {
              return data;
            }
          }
        }
      ]
    });
});

/**
 * jQuery plugin to convert text in a cell to a dropdown
 */
(function($) {
  $.fn.createDropDown = function(items) {
    let oldTxt = this.text();
    let isKnown = items.filter(function(k) { return k.id === oldTxt; }).length > 0;
    if (isKnown) {
      this.empty().append($('<select>').append(items.map(function(item) {
        let $option = $('<option>', {
          text: item.text,
          value: item.id
        });
        if (item.id === oldTxt) {
          $option.attr('selected', 'selected');
        }
        return $option;
      })));
    }
    return this;
  };
})(jQuery);

// If you remove the renderer above and change this to true,
// you can call this, but it will run once...
if (false) {
  $('#resdatatable > tbody tr').each(function(i, tr) {
    $(tr).find('td').last().createDropDown(statusList);
  });
}


function getStatusList() {
  return [{
    id: 'Confirmed',
    text: 'Confirmed'
  }, {
    id: 'Unconfirmed',
    text: 'Unconfirmed'
  }, {
    id: 'Open',
    text: 'Open'
  }, {
    id: 'Closed',
    text: 'Closed'
  }, {
    id: 'Canceled',
    text: 'Canceled'
  }];
}

function changeResStatus(str1) {
    var id = str1;
    var status = document.getElementById("resstatus" + id).value;
    var mailres = "";

    var r = confirm("Change Status for ID # " + id + " to " + status + "?");
    if (r == true) {

        if (document.getElementById("resstatus" + id).value == "Confirmed"){
            var s = confirm("Send ID # " + id + " a confirmation email?");
            if (s == true) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {

                document.getElementById("result").setAttribute ("data-notify-msg", this.responseText);
                document.getElementById("result").setAttribute ("data-notify-type", "info");
                SEMICOLON.widget.notifications(document.getElementById("result"));
            }
        };
        xmlhttp.open("GET","sendconfirmationemail.php?id="+id,true);
        xmlhttp.send();
        }
        }

        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("result").setAttribute ("data-notify-msg", this.responseText);
                document.getElementById("result").setAttribute ("data-notify-type", "info");
                SEMICOLON.widget.notifications(document.getElementById("result"));
            }
        };
        xmlhttp.open("GET","changeresstatus.php?id="+id+"&status="+status,true);
        xmlhttp.send();

    }else{
                document.getElementById("result").setAttribute ("data-notify-msg", "Change status action aborted");
                document.getElementById("result").setAttribute ("data-notify-type", "error");
                SEMICOLON.widget.notifications(document.getElementById("result"));
    }
    }

$(document).ready(function() {
    var table = $('#resdatatable').DataTable();

    $('#resdatatable tbody').on('click', 'tr', function () {
        var data = table.row( this ).data().id;


         $.ajax({
        type: 'POST',
        url: 'getreservationsdetails.php',
        dataType: 'json',
        data: {  id:data, },
        success: function(response) {
                $('#resulttitle').html("Booking ID # " + response[0].id);
                $('#resdetname').html(response[0].name);
                $('#resdetbdate').html(response[0].bookingdatetime);
                $('#resdetadd').html("<br>" + response[0].address + "<br>" + response[0].city + "<br>" + response[0].state + " " + response[0].post);
                $('#resdetphone').html(response[0].phone);
                $('#resdetemail').html(response[0].email);
                $('#resdetdln').html(response[0].dlnum);
                $('#resdetdle').html(response[0].dlexp);
                $('#resdetdlc').html(response[0].dlcountry);
                $('#resdetpickup').html(response[0].pickuploc + " " + response[0].pickupdatetime);
                $('#resdetduration').html(response[0].duration);
                $('#resdetdrop').html(response[0].droploc + " " + response[0].dropdatetime);
                $('#resdetclass').html(response[0].class);
                $('#resdetcoverage').html(response[0].coverage);
                $('#resdetage').html(response[0].age);
                $('#resdetnumofdrivers').html(response[0].numofdrivers);
                $('#resdetroadside').html(response[0].roadsideass);
                $('#resdetafterhoursdrop').html(response[0].afterhoursdrop);
                $('#resdetpromo').html(response[0].promo);
                $('#resdetquote').html(response[0].quote);
                $('#resdetaddcomments').html(response[0].name);
                $('#resdetip').html(response[0].ip);
                $("#modalresult").modal();
        }
    });



    } );
} );

Редактировать:

При дальнейшем рассмотрении эта ошибка, вероятно, вызвана строкой var table = $ ('# resdatatable'). DataTable(); в $ (document) .ready (function () {- если я удаляю эту строку, все работает просто отлично. Как мне заставить это работать ???

Ответы [ 2 ]

0 голосов
/ 19 октября 2019

Как я исправил эту проблему:

Я добавил задержку в 1 мс для запуска кода:

setTimeout(function() {
$(document).ready(function() {
                    var table = $('#resdatatable').DataTable();

    $('#resdatatable tbody').on('click', 'tr', function () {

        var data = table.row( this ).data().id;

         $.ajax({
        type: 'POST',
        url: 'getreservationsdetails.php',
        dataType: 'json',
        data: {  id:data, },
        success: function(response) {
                $('#resulttitle').html("Booking ID # " + response[0].id);
                $('#resdetname').html(response[0].name);
                $('#resdetbdate').html(response[0].bookingdatetime);
                $('#resdetadd').html("<br>" + response[0].address + "<br>" + response[0].city + "<br>" + response[0].state + " " + response[0].post);
                $('#resdetphone').html(response[0].phone);
                $('#resdetemail').html(response[0].email);
                $('#resdetdln').html(response[0].dlnum);
                $('#resdetdle').html(response[0].dlexp);
                $('#resdetdlc').html(response[0].dlcountry);
                $('#resdetpickup').html(response[0].pickuploc + " " + response[0].pickupdatetime);
                $('#resdetduration').html(response[0].duration);
                $('#resdetdrop').html(response[0].droploc + " " + response[0].dropdatetime);
                $('#resdetclass').html(response[0].class);
                $('#resdetcoverage').html(response[0].coverage);
                $('#resdetage').html(response[0].age);
                $('#resdetnumofdrivers').html(response[0].numofdrivers);
                $('#resdetroadside').html(response[0].roadsideass);
                $('#resdetafterhoursdrop').html(response[0].afterhoursdrop);
                $('#resdetpromo').html(response[0].promo);
                $('#resdetquote').html(response[0].quote);
                $('#resdetaddcomments').html(response[0].name);
                $('#resdetip').html(response[0].ip);
                $("#modalresult").modal();
        }
    });
0 голосов
/ 19 октября 2019

Ваша ошибка связана с тем, что вы пытаетесь получить доступ к объекту базы данных, который еще не был инициализирован getRes().

Поскольку на $(document).ready вы создавали первую базу данных без опций, когда getRes получил триггер, вы должны обновить ее содержимое вместо создания второй базы данных () поверх того же элемента (что объясняет «Cannot»). переинициализировать DataTable ")

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

$(document).ready(function() {

    $('#resdatatable tbody').on('click', 'tr', function () {
        var table = $('#resdatatable').DataTable();
        var data = table.row( this ).data().id;

Или, возможно, инициализировать $('#resdatatable tbody').on в getRes(), так как это может не иметьДоступ к телу пока нет:

getRes(function (result) { // APPLIED CALLBACK
  $('#resdatatable').DataTable({
    ...
  });

   $('#resdatatable tbody').on('click', 'tr', function () {
   ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...