javascript - 为什么 jQuery.sortable 的 ajax 会多次执行更新?

标签 javascript php jquery ajax jquery-ui

这是这个问题的延续:jQuery UI Sortable, then write order into a database

问题如下:

I want to use the jQuery UI sortable function to allow users to set an order and then on change, write it to the database and update it. Can someone write an example on how this would be done?

由于我需要能够快速重新订购东西,我认为这会非常有用。然而,公认的解决方案存在一个大问题。我在这里引用答案:

Here's a quick example that sends the data to the specified URL as soon as an element has changes position.

$('#element').sortable({
    axis: 'y',
    update: function (event, ui) {
        var data = $(this).sortable('serialize');

        // POST to server using $.post or $.ajax
        $.ajax({
            data: data,
            type: 'POST',
            url: '/your/url/here'
        });
    }
});

What this does is that it creates an array of the elements using the elements id. So, I usually do something like this:

<ul id="sortable">
   <li id="item-1"></li>
   <li id="item-2"></li>
   ...
</ul>

When you use the serialize option, it will create a POST query string like this: item[]=1&item[]=2 etc. So if you make use - for example - your database IDs in the id attribute, you can then simply iterate through the POSTed array and update the elements' positions accordingly.

For example, in PHP:

$i = 0;

foreach ($_POST['item'] as $value) {
    // Execute statement:
    // UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
    $i++;
}

此解决方案的问题是:它不仅会在您每次移动项目时更新一次,而且还会“存储”其他更新并在您进行更新之前执行它们。因此,例如,如果您移动 4 个项目,它将更新 1+2+3+4 次,从而导致更多可能的错误,并且如果您需要管理大量项目,则会使网页变慢。

我的问题很简单:为什么会发生这种情况?我怎样才能避免这种情况?

最佳答案

这个问题的答案确实非常简单(感谢Lucas Krupinski)。事实上,它所需要的只是添加一个按钮或类似的东西,并让它处理更新。

假设我添加了一个带有 onclick="save()" 的按钮。如果我们保留这样的代码:

$( function() {
    $( "#sortable" ).sortable();
    $( "#sortable" ).disableSelection();
} );

function save(){
    var order = $("#sortable").sortable('serialize');
    console.log("order: " + order);
    $.ajax({
        data: order,
        type: 'POST',
        url: '/your/url/here'
    });
}

我们将看到脚本仅按照我们现在的顺序执行一次,避免了性能下降和顺序错误。

关于javascript - 为什么 jQuery.sortable 的 ajax 会多次执行更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45917601/

相关文章:

php在终端执行时无法连接到数据库

javascript - angularjs 数据表按钮插件

javascript - jquery 条件不适用于所选属性

javascript - AngularJS 指令中的元素高度

javascript - Laravel 如何根据查询按天渲染成融合图表

javascript - iframe从php文件设置src值,而不在源代码中显示文件路径

jquery - Ajax : How to prevent jQuery from calling the success event after executing xmlHttpRequest. 中止();

javascript - FeathersJS 中的非 CRUD 路由

javascript - 如何验证nodejs中的jwt token /永不过期?

javascript - 获取url参数并在jquery对话框中显示