jquery - 如何通过ajax将项目ID发送到服务器: jquery sortable

标签 jquery html ajax jquery-ui

我有一组图像需要重新排列。所以我把图像放在它的 div 中。我可以替换它,但它不会通过 ajax 发送 id。

html

<div class="row sortable">
  <div class="col-sm-4" id="1">
    <img src="//via.placeholder.com/200x150" />
  </div>

  <div class="col-sm-4" id="2">
    <img src="//via.placeholder.com/200x150" />
  </div>

  <div class="col-sm-4" id="3">
    <img src="//via.placeholder.com/200x150" />
  </div>
</div>

js

$('.sortable').sortable({
  update: function(event, ui) {
    $.ajax({
      data: $(this).sortable('serialize'),
      type: 'POST',
      url: '/echo/json/', 
      success: function(data) {
        console.log(data);
      }
    });
  }
});

这是我的 fiddle :http://jsfiddle.net/bmp6xoog/3/

最佳答案

文档明确指出

It works by default by looking at the id of each item in the format "setname_number", and it spits out a hash like "setname[]=number&setname[]=number".

Note: If serialize returns an empty string, make sure the id attributes include an underscore. They must be in the form: "set_number".
For example, a 3 element list with id attributes "foo_1", "foo_5", "foo_2" will serialize to "foo[]=1&foo[]=5&foo[]=2".
You can use an underscore, equal sign or hyphen to separate the set and number.
For example "foo=1", "foo-1", and "foo_1" all serialize to "foo[]=1".

您使用的 ID 仅包含数字,这就是它不起作用的原因,它必须是格式为 foo_1 等的 ID。

$('.sortable').sortable({
  update: function(event, ui) {
    console.log( $(this).sortable('serialize') ); // works
    
    $.ajax({
      data: $(this).sortable('serialize'),
      type: 'POST',
      url: '/echo/json/', 
      success: function(data) {
        console.log(data);
      }
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>


<div class="row sortable">
  <div class="col-sm-4" id="item_1"> <!-- like this -->
    <img src="//via.placeholder.com/200x150" />
  </div>

  <div class="col-sm-4" id="item_2"> <!-- and this -->
    <img src="//via.placeholder.com/200x150" />
  </div>

  <div class="col-sm-4" id="item_3"> <!-- and this -->
    <img src="//via.placeholder.com/200x150" />
  </div>
</div>

关于jquery - 如何通过ajax将项目ID发送到服务器: jquery sortable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46004115/

相关文章:

jquery - 如何防止 jquery Ajax 调用滚动带有输入到浏览器窗口顶部的表单

jquery - 如何在 MVC 中绑定(bind) HandsonTables

jquery - 平滑修改 css 剪辑路径

javascript - 获取不同名称的单选按钮的表单数据

javascript - 如何在 UI5 中处理 jQuery POST 的 X-CSRF-Token?

html - nth-of-type 仅适用于 1 和 2

javascript - 表单验证是否有任何字段具有值。否则提交空

javascript - 从使用 getElementsByClassName() 创建的数组中获取值

html - 如何在剪辑路径形状周围制作边框?

javascript - 使用 html5、jquery、ajax 比较日期