source

jQuery UI 정렬 가능, 데이터베이스에 순서 쓰기

manysource 2022. 12. 13. 20:08

jQuery UI 정렬 가능, 데이터베이스에 순서 쓰기

jQuery UI를 사용하고 싶다sortable사용자가 순서를 설정한 후 변경할 수 있도록 하는 기능을 사용하여 데이터베이스에 기록하고 업데이트합니다.누가 어떻게 해야 하는지 예를 들어줄 수 있나요?

jQuery UI 기능에는 이를 위한 방법이 포함되어 있습니다.꽤 간단해, 정말로.다음은 요소의 위치가 변경되는 즉시 지정된 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'
        });
    }
});

이렇게 하면 요소를 사용하여 요소의 배열을 생성할 수 있습니다.id그래서 저는 이런 걸 많이 해요.

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

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

예를 들어 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 서버에서 목록을 가져와 정렬하면 다음 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>

운이 좋으시네요, 제 CMS에 있는 것과 똑같은 것을 사용하고 있어요.

주문을 저장하고 싶을 때는 JavaScript 메서드를 호출하기만 하면 됩니다.saveOrder()AJAX를 만듭니다.POSTsave order.displays를 요청하지만 물론 일반 형식으로 언제든지 게시할 수 있습니다.

<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();'/>

저장 순서php; 모든 검증과 확인을 삭제했습니다.

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

이게 제 예시입니다.

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

업데이트 이벤트에서 주문을 잡아야 합니다.

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

jsFiddle에서 승인된 답변과 관련된 예를 따라 행을 변경할 수 있습니다.그러나 알 수 없는 이유로 인해 "정지 또는 변경" 작업 후 ID를 가져올 수 없었습니다.그러나 JQuery UI 페이지에 게시된 예제는 문제없이 작동합니다.이 링크는 이쪽에서 확인하실 수 있습니다.

다음 솔루션을 사용해 보십시오.http://phppot.com/php/sorting-mysql-row-order-using-jquery/ 에서는 일부 HMTL 요소에 새 순서가 저장됩니다.그런 다음 이 데이터와 함께 폼을 PHP 스크립트에 제출하고 for loop을 사용하여 반복합니다.

주의: INT(11) 유형의 다른 db 필드를 추가해야 합니다.이는 반복할 때마다 갱신(타임 스탬프)됩니다.이 필드는 스크립트에서 최근에 갱신된 행을 인식하기 위한 역할을 합니다.그렇지 않으면 스크램블된 결과가 나타납니다.

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