0
Rail 5.2
datatables

在我的views/books/index.html.slim 中,我正在从另一个MVC 加载部分内容,如下所示:

 = render  partial: 'authors/index', :locals => {:author => @book.author}

在我的意见/作者/_index.html 中,我有以下内容:

.....    
table.table-striped.table-bordered.table-hover.nowrap#AuthorsIndex.display
.....

javascript:
  $('#AuthorsIndex').DataTable({
    ajax: '/authors',
    columns: [
      {title: 'Publish Date', data: 'created_at'},
      {title: 'Publisher', data: 'publisher'},
      {title: 'Title', data: 'title'},
    ]
  });

而且,在我的 controllers/authors_controllers.rb 中,我有以下内容:

def index
  @authors = Author.where(author: "John Doe")
  render json: { data: @authors }
end

当我运行它时,作者表正确显示。问题是作者姓名在控制器操作中是硬编码的。我的 _index 部分,正在接收作者姓名,但是作为我正在进行的 Ajax 调用的一部分,我如何将其发送给作者控制器?Ajax/Javascript 新手。

4

2 回答 2

1

我没有安装必要的工具来测试它,但是 jQuery DataTable 文档说您可以通过该ajax.data选项提供自定义数据。

ajax.data选项提供了向请求添加额外数据的能力,或者在需要时修改提交的数据对象。

...

作为一个对象,该ajax.data选项用于扩展DataTables内部构造的数据对象以提交给服务器。这提供了一种向要发送到服务器的数据添加附加静态参数的简单方法。对于动态计算的值,ajax.data用作函数(见下文)。

该文档还提供了示例场景,并进一步详细说明了可以提供的内容。

$('#AuthorsIndex').DataTable({
  ajax: {
    url: '/authors',
    data: {author: '<%= j author %>'}
  },
  columns: [
    {title: 'Publish Date', data: 'created_at'},
    {title: 'Publisher',    data: 'publisher'},
    {title: 'Title',        data: 'title'}
  ]
});

然后在控制器中:

def index
  @authors = Author.where(author: params[:author])
  render json: { data: @authors }
end
于 2019-10-31T13:19:00.257 回答
1

How about

#_index.html
javascript:
  $('#AuthorsIndex').DataTable({
    ajax: '/authors?author=<%= author %>',
    columns: [
      {title: 'Publish Date', data: 'created_at'},
      {title: 'Publisher', data: 'publisher'},
      {title: 'Title', data: 'title'},
    ]
  });

#authors_controllers.rb
def index
  @authors = Author.where(author: params[:author])
  render json: { data: @authors }
end
于 2019-10-31T13:19:42.433 回答