当一张卡片被拖入列表中时,我将使用jQueryUI可排序插件的update回调将每个卡片的新位置发送给我的控制器。此AJAX请求将张贴每个卡片的position属性,无论被拖拽的卡片是在哪个列表中释放的。
$(".js-Sortable").sortable({
connectWith: ".js-Sortable",
items: ".js-CardContainer",
update: function( event, ui ) {
if (this === ui.item.parent()[0]) {
var data = $(this).sortable('serialize');
$.ajax({
url: "/c/sort",
type: "POST",
dataType: "script",
data: data,
success: function(resp){
console.log('Yay');
}
});
}
}
});这将发送类似如下所示的参数
Parameters: {"card"=>["39", "2", "1", "6", "40", "5", "18", "3", "16", "7", "17", "8", "15", "9", "10", "11", "12", "13", "14", "4"]}然后在我的控制器操作中更新每个受影响的卡的position属性,如下所示:
def sort
params[:card].each_with_index do |id, index|
card = Card.find(id)
card.update_attribute(:position, index) if card
end
head :ok
end视图如下所示:
<ul class="js-CardsContainer js-Sortable">
<% list.cards.order(:position).where(archived: false).each do |card| %>
<li class="js-CardContainer" id="card-<%= card.id %>">
<%= link_to card, class: 'js-Card', :data => { :id => card.id }, remote: true do %>
<span><%= card.title %></span>
<% end %>
</li>
<% end %>
</ul>到目前为止,这些都是有效的。问题是,卡片可以在不同的列表中移动。因此,我需要以某种方式获取被拖拽的卡在其中释放的列表的id,并将其与AJAX请求一起发布。
我可以将list_id作为变量获取,但是如何将此list_id添加到AJAX请求中的数组中呢?
发布于 2017-07-09 21:12:06
根据您的问题,您将获得cards_id,并且您希望传递list_id
在DOM中,您需要首先添加list_id
<%= link_to card, class: 'js-Card', :data => { :id => card.id }, remote: true,"data-list-id":list.id do %>
<span><%= card.title %></span> <% end %>现在,您需要在事件处理程序中获取此列表id,并将其与cards_id参数组合在一起
$(".js-Sortable").sortable({
connectWith: ".js-Sortable",
items: ".js-CardContainer",
update: function( event, ui ) {
if (this === ui.item.parent()[0]) {
var data = {}
var data['cards_id'] = $(this).sortable('serialize');
var data['list_id'] = $(this).attr("data-list-id")
$.ajax({
url: "/c/sort",
type: "POST",
dataType: "script",
data: data,
success: function(resp){
console.log('Yay');
}
});
}
}
});在您的控制器排序操作中,您需要遵循以下代码
params[:card].each_with_index do |id, index, list_id|
card = Card.find(id)
card.update(:position => index,
:list_id => params[:ListId])
end希望它能帮上忙
发布于 2017-07-09 23:24:00
抱歉,我回复晚了。为了构建@uzaif的答案,您还可以在数据散列本身内部设置键值对,如下所示:
var data = {$(this).sortable('serialize'), list_id: $(this).attr("data-list-id")}就像@uzaif所说的,确保调整你的控制器以接受参数散列中的list_id。
发布于 2017-07-10 02:13:53
正如我在前面的评论中提到的,在排序这样的事件上(以及在其他jquery UI事件中,比如draggable)发送的对象中,至少有一个对象通常包含对前一个元素的引用。
在本例中,ui对象包含一个发送者数组,该数组将包含索引为0的对最近发送者的引用:ui.sender[0]
我在这里给出了一个示例,说明如何在您的案例中使用此方法:
http://jsfiddle.net/6npx24uf/
https://stackoverflow.com/questions/44982675
复制相似问题