使用rails的jQuery序列化对自定义id不起作用

jQuery serialize using rails doesn't work for custom ids

本文关键字:自定义 id 不起作用 序列化 rails jQuery 使用      更新时间:2023-09-26

我很确定这是某种Javascript错误,而不是在我的id上做了无数次put()试验后的Rails错误…

我要做的是用jQuery的serialize函数序列化一堆li。我想基于一组自定义id来做。在我的例子中,podli-1, podli-2, podli-3等等。我尝试通过使用serialize "expression"选项来做到这一点。

当我尝试用警报调试它时(如下所示),我得到的结果是:id=undefined&id=undefined&id=undefined&id=undefined&id=undefined&id=undefined&id= undefined&id=undefined&id=undefined&id=undefined&id=undefined&id=undefined&

——这实际上是正确的li的数目,但由于某种原因,所有的id都是未定义的。正如我所说的,这一切都在Rails中工作,但有一些JS错误。

下面是Rails代码。

<% @pods.each do |podli| %>
<% @podli = podli %>
<% @iden = 'podli-' << @podli.id.to_s %>
<li id="<%= @iden %>" class="ui-state-default">
   ....
</li>
<% end %>

这里是javascript

$(document).ready(function(){
transitions();
//$( "#sortable" ).sortable({containment: 'parent'});
$(  "#sortable"  ).sortable({ items: '.ui-state-default', containment: 'parent'})//for moving the pods about
$( "#sortable" ).disableSelection();
//$("#newspod" ).val("Enable Sort").closest("#newspod").removeClass("sortable")
$('#sortable').live('sortstop', function(event) {
    var u = $(this).sortable('serialize', { key: 'id', expression: /podli-'d/ })//  + '&index=' + jQuery(this).attr("id").substring(19);
    alert(u);
    $.ajax({
      type: 'POST', 
      data: { display_order: u },//$('#receiving-list').sortable('serialize')  + '&index=' + jQuery(this).attr("id").substring(19), 
      url: "<%= sort_dashboards_path %>"
    })
});

});

当你调用"serialize"方法时(通过"sortable"插件),你的"expression" regex必须包含一个捕获组,无论值应该是什么:

 var u = $(this).sortable('serialize', { key: 'id', expression: /podli-('d+)/ });

通过将"'d"(注意,我不能帮助自己,我添加了"+",以防你有超过10个)包装在括号中,插件将从你的正则表达式中得到它所期望的。