首页 > 解决方案 > Rails 5.2 数据表不会在页面更改时刷新数据

问题描述

我有一个配置了数据表的 rails 5.2 项目。该插件工作正常,但如果我更改页面然后点击后退按钮,表中的数据不会再次使用数据表加载。它说“表中没有数据”。对我来说,这听起来像是一个 turbolinks 问题。

我正在使用以下内容生成表:

$( document ).on('turbolinks:load', function() {
  $("#prjtbl").dataTable();
});

数据表插件在页面更改之间加载,但表中的数据不会刷新。有想法该怎么解决这个吗?

更新:Application.js

        // This is a manifest file that'll be compiled into application.js, which will include all the files
    // listed below.
    //
    // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
    // vendor/assets/javascripts directory can be referenced here using a relative path.
    //
    // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
    // compiled file. JavaScript code in this file should be added after the last require_* statement.
    //
    // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
    // about supported directives.
    //
    //= require rails-ujs
    //= require jquery
    //= require datatables
    //= require popper
    //= require bootstrap-sprockets
    //= require shards-dashboards
    //= require trix
    //= require activestorage
    //= require turbolinks
    //= require_tree .

页面.js

    JQuery(function() {
      $( document ).on('turbolinks:load', function() {
        $("#prjtbl").dataTable();
      });
    });

标签: ruby-on-railsdatatablesruby-on-rails-5

解决方案


document.addEventListener("turbolinks:load", function() {
  "use strict";
  if ($("#prjtbl").length == 0) {
    $("#prjtbl").dataTable();
  }
})

推荐阅读