将Json响应传递到Rails Ajax Datatable中的视图



我有一个索引方法,它用Json调用来响应Datatable,例如:

respond_to do |format|
format.html
format.json { render json: PeopleDatatable.new(params, user: current_user, view_context: view_context) }
end

我希望能够将响应中所有ID的数组传递给我视图中的dom,例如<div id: "people">1,2,3,4</div>

根据gem描述,人员记录在中生成

app/datatables/people_datatable.rb

使用:

def get_raw_records
User.all
end

我尝试在视图的脚本中添加以下内容:

$(document).ready(function () {
$.ajax({
type: "GET",
url: "<%= peoples_path(format: :json) %>",
dataType: "json",
success: function(data) {
alert(data.name)
$('#bouba').html(data);
}
});
});

但是结果是一个未定义的对象类。

请问最简单的方法是什么?

我将以下gem用于我的数据表Rails ajax数据表

打开/people.json,看看你得到了什么响应,它看起来像这样:

{
"recordsTotal": 2,
"recordsFiltered": 2,
"data": [
{
"id": "1",
"name": ""
},
{
"id": "2",
"name": ""
},
]
}

既然您知道了结构的样子,那么就向该url发送ajax请求:

<div id="people-ids"></div>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
// send request to the correct url: "/people.json"
url: "<%= people_path(format: :json) %>",
dataType: "json",
success: function({data}) {
//              ^
// extract "data" attribute from the response
console.log(data) // you can see what you get in the console

// extract ids
const user_ids = data.map(user => user.id)
// do what you like with the ids
$("#people-ids").html(user_ids.join());
}
});
});
</script>

最新更新