IT박스

jQuery UI Sortable 다음 데이터베이스에 순서를 씁니다.

itboxs 2020. 7. 15. 07:56
반응형

jQuery UI Sortable 다음 데이터베이스에 순서를 씁니다.


jQuery UI sortable함수를 사용하여 사용자가 주문을 설정 한 다음 변경시 데이터베이스에 기록하고 업데이트 할 수 있도록 하고 싶습니다 . 누군가 이것이 어떻게 수행되는지에 대한 예를 쓸 수 있습니까?


jQuery UI sortable기능에는 이를 수행 하는 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'
        });
    }
});

이것이하는 것은 elements를 사용하여 요소의 배열을 만드는 것 id입니다. 그래서 나는 보통 다음과 같이합니다 :

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

serialize옵션 을 사용하면 다음 과 같은 POST 쿼리 문자열이 생성됩니다 item[]=1&item[]=2. 예를 들어 id속성 에서 데이터베이스 ID를 사용하는 경우 POST 된 배열을 반복하고 그에 따라 요소의 위치를 ​​업데이트 할 수 있습니다. .

예를 들어, PHP에서 :

$i = 0;

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

jsFiddle의 예.


이것이 도움이 될 것이라고 생각했습니다. A) 각 정렬 후 서버로 다시 보내는 동안 페이로드를 최소로 유지하도록 설계되었습니다. (매번 모든 요소를 ​​보내거나 서버가 막을 수있는 많은 요소를 반복하는 대신) B) 요소의 id / 이름을 손상시키지 않고 사용자 정의 ID를 다시 보내야했습니다. 이 코드는 asp.net 서버에서 목록을 가져온 다음 정렬시 두 가지 값만 다시 전송됩니다. 정렬 된 요소의 db id 및 삭제 된 요소 옆의 요소의 db id. 이 두 값을 기반으로 서버는 새 위치를 쉽게 식별 할 수 있습니다.

<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>

운 좋게도 CMS에서 정확한 것을 사용합니다

주문을 저장하려면 JavaScript 메소드를 호출하십시오 saveOrder(). POSTsaveorder.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.

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

This is my example.

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});
    }
});

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.


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.

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.

참고URL : https://stackoverflow.com/questions/15633341/jquery-ui-sortable-then-write-order-into-a-database

반응형