通过 Ajax 调用将变量传递给控制器

Passing variable to controller through Ajax call

Rail 5.2
datatables

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

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

在我的 views/authors/_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

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

的新手

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

The ajax.data option provides the ability to add additional data to the request, or to modify the data object being submitted if required.

...

As an object, the ajax.data option is used to extend the data object that DataTables constructs internally to submit to the server. This provides an easy method of adding additional, static, parameters to the data to be sent to the server. For dynamically calculated values, use ajax.data as a function (see below).

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

$('#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

怎么样

#_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