将存储在localStorage中的jQuery可拖动位置保存到MySQL

时间:2018-03-15 06:31:03

标签: javascript php jquery mysql

我使用以下脚本来跟踪和保存多个可拖动的 图像位置到localStorage。

https://jsfiddle.net/jakecigar/v685v9t6/31/

var positions = JSON.parse(localStorage.positions || "{}");
$(function () {
    var d = $("[id=draggable]").attr("id", function (i) {
        return "draggable_" + i
    })
    $.each(positions, function (id, pos) {
        $("#" + id).css(pos)
    })

    d.draggable({
        containment: "#containment-wrapper",
        scroll: false,
        stop: function (event, ui) {
            positions[this.id] = ui.position
            localStorage.positions = JSON.stringify(positions)
        }
    });
});

在php / html方面,我想通过提交按钮,将这些位置写入MySQL数据库,并以相同的方式从数据库中恢复它们。

1 个答案:

答案 0 :(得分:0)

这是修改后的javascript代码,允许将位置写入数据库并重新加载。

<script type="text/javascript">
    $(document).ready(function() {
        var positions = JSON.parse(localStorage.positions || "{}");
        $(function() {
            var d = $("[id=draggable]").attr("id", function(i) {
                return "draggable_" + i
            })


            $.each(positions, function(id, pos) {
                $("#" + id).css(pos)
            })

            d.draggable({
                containment: "#containment-wrapper",
                scroll: false,
                stop: function(event, ui) {
                    positions[this.id] = ui.position
                    localStorage.positions = JSON.stringify(positions)
                }
            });
            $(".saveable").click(function() {
                $.ajax({
                    type: 'POST',
                    url: 'mysql-write.php',
                    data: {
                        myVar: JSON.stringify(positions),
                    },
                    success: function(data) {
                        console.log(data);
                    }
                });
            });


            $(".loadable").click(function() {
                $.ajax({
                    url: 'mysql-read.php',
                    dataType: 'json'
                }).done(
                    function(data) {
                        var newpos = data[0];
                        var positions = JSON.parse(newpos);
                        $.each(positions, function(id, pos) {
                            $("#" + id).css(pos)
                        })
                        localStorage.positions = newpos
                    }
                );
            });
        });
    });
</script>

mysql-read.php应该提取数据。

echo json_encode(array($row['data']));

mysql-write.php应该写入传递给DB的变量。

$writethis = $_POST['myVar'];