我有一组图像需要重新排列。所以我把图像放在它的 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/