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


Rail 5.2
datatables

在我的视图/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

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

怎么样

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

我没有安装必要的工具来测试这一点,但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