php jQuery UI Sortable,然后将订单写入数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15633341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:39:26  来源:igfitidea点击:

jQuery UI Sortable, then write order into a database

phpjquerymysqljquery-uijquery-ui-sortable

提问by Harry

I want to use the jQuery UI sortablefunction 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?

我想使用 jQuery UIsortable功能来允许用户设置订单,然后更改,将其写入数据库并更新它。有人可以写一个关于如何做到这一点的例子吗?

回答by Knelis

The jQuery UI sortablefeature includes a serializemethodto do this. It's quite simple, really. Here's a quick example that sends the data to the specified URL as soon as an element has changes position.

jQuery UIsortable功能包含一种serialize方法来执行此操作。这很简单,真的。这是一个快速示例,它在元素更改位置后立即将数据发送到指定的 URL。

$('#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:

它的作用是使用元素创建一个元素数组id。所以,我通常会做这样的事情:

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

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

当您使用该serialize选项时,它将创建一个 POST 查询字符串,如下所示:item[]=1&item[]=2等。因此,如果您在id属性中使用 - 例如 - 您的数据库 ID ,您可以简单地遍历 POSTed 数组并相应地更新元素的位置.

For example, in PHP:

例如,在 PHP 中:

$i = 0;

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

Example on jsFiddle.

jsFiddle 上的示例。

回答by Kalpesh Popat

Thought this might help as well. A) it was designed to keep payload to its minimum while sending back to server, after each sort. (instead of sending all elements each time or iterating through many elements that server might chuck out) B) I needed to send back custom id without compromising the id / name of the element. This code will get the list from asp.net server and then upon sorting only 2 values will be sent back: The db id of sorted element and db id of the element next to which it was dropped. Based on those 2 values, server can easily identify the new postion.

认为这也可能有所帮助。A)它旨在在每次排序后将有效负载发送回服务器时将其保持在最低限度。(而不是每次都发送所有元素或遍历服务器可能会退出的许多元素)B)我需要在不影响元素的 id / name 的情况下发回自定义 id。此代码将从 asp.net 服务器获取列表,然后在排序时仅发送 2 个值:已排序元素的 db id 和删除它的旁边元素的 db id。基于这 2 个值,服务器可以轻松识别新位置。

<div id="planlist" style="width:1000px">
    <ul style="width:1000px">
       <li plid="listId1"><a href="#pl-1">List 1</a></li>
       <li plid="listId2"><a href="#pl-2">List 1</a></li>
       <li plid="listId3"><a href="#pl-3">List 1</a></li>
       <li plid="listId4"><a href="#pl-4">List 1</a></li>
    </ul>
    <div id="pl-1"></div>
    <div id="pl-2"></div>
    <div id="pl-3"></div>
    <div id="pl-4"></div>
</div>
<script type="text/javascript" language="javascript">
    $(function () {
        var tabs = $("#planlist").tabs();
        tabs.find(".ui-tabs-nav").sortable({
            axis: "x",
            stop: function () {
                tabs.tabs("refresh");
            },
            update: function (event, ui) {
                //db id of the item sorted
                alert(ui.item.attr('plid'));
                //db id of the item next to which the dragged item was dropped
                alert(ui.item.prev().attr('plid'));

                //make ajax call
            }
        });
    });
</script>

回答by Hugo Delsing

You're in luck, I use the exact thing in my CMS

你很幸运,我在我的 CMS 中使用了确切的东西

When you want to store the order, just call the JavaScript method saveOrder(). It will make an AJAX POSTrequest to saveorder.php, but of course you could always post it as a regular form.

当您要存储订单时,只需调用 JavaScript 方法即可saveOrder()。它将POST向 saveorder.php发出 AJAX请求,但当然您可以始终将其作为常规表单发布。

<script type="text/javascript">
function saveOrder() {
    var articleorder="";
    $("#sortable li").each(function(i) {
        if (articleorder=='')
            articleorder = $(this).attr('data-article-id');
        else
            articleorder += "," + $(this).attr('data-article-id');
    });
            //articleorder now contains a comma separated list of the ID's of the articles in the correct order.
    $.post('/saveorder.php', { order: articleorder })
        .success(function(data) {
            alert('saved');
        })
        .error(function(data) { 
            alert('Error: ' + data); 
        }); 
}
</script>
<ul id="sortable">
<?php
//my way to get all the articles, but you should of course use your own method.
$articles = Page::Articles();
foreach($articles as $article) {
    ?>
    <li data-article-id='<?=$article->Id()?>'><?=$article->Title()?></li>
    <?
}               
?>   
</ul>
   <input type='button' value='Save order' onclick='saveOrder();'/>

In saveorder.php; Keep in mind I removed all verification and checking.

在 saveorder.php 中;请记住,我删除了所有验证和检查。

<?php
$orderlist = explode(',', $_POST['order']);
foreach ($orderlist as $k=>$order) {
  echo 'Id for position ' . $k . ' = ' . $order . '<br>';
}     
?>

回答by luisnicg

This is my example.

这是我的例子。

https://github.com/luisnicg/jQuery-Sortable-and-PHP

https://github.com/luisnicg/jQuery-Sortable-and-PHP

You need to catch the order in the update event

您需要在更新事件中捕获订单

    $( "#sortable" ).sortable({
    placeholder: "ui-state-highlight",
    update: function( event, ui ) {
        var sorted = $( "#sortable" ).sortable( "serialize", { key: "sort" } );
        $.post( "form/order.php",{ 'choices[]': sorted});
    }
});

回答by Web_Developer

I can change the rows by following the accepted answer and associated example on jsFiddle. But due to some unknown reasons, I couldn't get the ids after "stop or change" actions. But the example posted in the JQuery UI page works fine for me. You can check that link here.

我可以按照 jsFiddle 上接受的答案和相关示例更改行。但是由于一些未知的原因,我无法在“停止或更改”操作后获取 ID。但是 JQuery UI 页面中发布的示例对我来说效果很好。您可以在此处查看该链接。

回答by TomoMiha

Try with this solution: http://phppot.com/php/sorting-mysql-row-order-using-jquery/where new order is saved in some HMTL element. Then you submit the form with this data to some PHP script, and iterate trough it with for loop.

尝试使用此解决方案:http: //phppot.com/php/sorting-mysql-row-order-using-jquery/,其中新订单保存在某些 HMTL 元素中。然后您将带有此数据的表单提交给某个 PHP 脚本,并使用 for 循环对其进行迭代。

Note: I had to add another db field of type INT(11) which is updated(timestamp'ed) on each iteration - it serves for script to know which row is recenty updated, or else you end up with scrambled results.

注意:我必须添加另一个 INT(11) 类型的 db 字段,它在每次迭代时更新(时间戳) - 它用于让脚本知道最近更新了哪一行,否则你最终会得到混乱的结果。