jQuery自动保存无法正常工作


jQuery autosave not working as it should

我在下面写了几个脚本,它们单独工作很好,但放在一起却不能正常工作。让我发布代码,然后解释问题:

自动保存功能:

<script>
        function autosave() {
            $('form').each(function() {
                var string = $(this).closest('form').serialize();
                var $this = $(this);
                $.ajax({
                type: "POST",
                url: "add_room.php",
                data: string,
                cache: false,
                success: function(data){
                    var saveIcon = $this.siblings('.saveIcon');
                    $this.siblings('[type=hidden]').val(data);
                    saveIcon.fadeIn(750);
                    saveIcon.delay(500).fadeOut(750);
                    $('#message').text('The id of the inserted information is ' + data);
                }
                });
            });
        }
        setInterval(autosave, 10 * 1000);
</script>

AJAX发布和返回脚本:

<script>
    $(document).ready(function() {
        $('body').on('click', '.save', function(e) {
            var string = $(this).closest('form').serialize();
            var $this = $(this);
            $.ajax({
                type: "POST",
                url: "add_room.php",
                data: string,
                cache: false,
                success: function(data){
                    var saveIcon = $this.siblings('.saveIcon');
                    $this.siblings('[type=hidden]').val(data);
                    saveIcon.fadeIn(750);
                    saveIcon.delay(500).fadeOut(750);
                    $('#message').text('The id of the inserted information is ' + data);
                }
            });
        });
    });
    $(document).ready(function(){
        $('#addForm').on('click', function(){
            $('<form method="post" action="add_room.php"><label for="itemName[]">Item</label><input type="text" name="itemName[]"><label for="itemPhoto[]">Photo</label><input type="text" name="itemPhoto[]"><input type="hidden" name="itemId[]" value=""><input type="hidden" name="itemParent[]" value="<?=$_GET["room"]?>"><div class="saveIcon" style="display: none; color: green;">SAVED!</div><div class="save">Save Item</div></form>').fadeIn(500).appendTo('.addItem');
        });
    });
</script>

形式:

<form method="post" action="add_room.php">
                <label for="itemName[]">Item</label>
                <input type="text" name="itemName[]">
                <label for="itemPhoto[]">Item</label>
                <input type="text" name="itemPhoto[]">
                <input type="hidden" name="itemId[]" value="">
                <input type="hidden" name="itemParent[]" value="<?=$_GET['room']?>">
                <div class="saveIcon" style="display: none; color: green;">SAVED!</div>
                <div class="save">Save Item</div>
</form>

PHP:

<?PHP
    require_once('dbConfig.php');
    $item = $_POST['itemName'];
    $photo = $_POST['itemPhoto'];
    $id = $_POST['itemId'];
    $parentId = $_POST['itemParent'];
    foreach($item as $key => $val) {
        if(!$id[$key]) {
            if ($stmt = $db->prepare("INSERT test (test_title, test_desc, test_parent) VALUES (?, ?, ?)"))
            {
                // Use an s per variable passed to the string, example - "ss", $firstname, $lastname
                $stmt->bind_param("ssi", $val, $photo[$key], $parentId[$key]);
                $stmt->execute();
                $stmt->close();
                echo $db->insert_id;
                //echo "success";
            }
            // show an error if the query has an error
            else
            {
                echo "ERROR: Could not prepare Insert SQL statement.";
            }
        } 
            else
        {
            if ($stmt = $db->prepare("UPDATE test SET test_title = ?, test_desc = ? WHERE test_id = ?"))
            {
                // Use an s per variable passed to the string, example - "ss", $firstname, $lastname
                $stmt->bind_param("ssi", $val, $photo[$key], $id[$key]);
                $stmt->execute();
                $stmt->close();
                echo $id[$key];
                //echo "success";
            }
            // show an error if the query has an error
            else
            {
                echo "ERROR: Could not prepare Update SQL statement.";
            }
        }
    }
?>

现在,第二个脚本的情况是,当在没有自动保存的情况下单独使用时,当您填写表单并单击"保存"时,它会获取表单数据并将其保存到数据库中必要的行中,然后返回刚刚保存的id,并将数据放在一个隐藏字段中,这样php脚本就可以确定是需要插入查询还是需要更新查询(当返回的id存在时)。还有一个名为addForm的可点击div,它会在现有表单的下面添加另一个表单集,当单击保存按钮时,只会在数据库中保存/更新此表单。当我像在代码中那样触发自动保存时,自动保存会接收所有表单并将其保存为新条目,但不会返回id/update隐藏字段以触发更新序列。你能阐明这一点吗?这真的很烦我。我已经尽力解释了,对不起,时间太长了。这有点复杂!哈哈

我建议对代码的组织进行一些更改,这样可以更容易地识别错误。

http://pastebin.com/0QTZzX6X

function postForm(form) {
    var $this = $(form);
    var string = $this.serialize();
    $.ajax({
        type: "POST",
        url: "add_room.php",
        data: string,
        cache: false,
        success: function(data){
            var saveIcon = $this.find('.saveIcon');
            $this.find('[type=hidden]').val(data);
            saveIcon.fadeIn(750);
            saveIcon.delay(500).fadeOut(750);
            $('#message').text('The id of the inserted information is ' + data);
        }
    });
}
function autosave() {
    $('form').each(function() {
        postForm(this);
    });
}
setInterval(autosave, 10 * 1000);
$(document).ready(function() {
    $('body').on('click', '.save', function(e) {
        postForm($(this).closest('form').get(0));
    });
    $('#addForm').on('click', function(){
        $('<form method="post" action="add_room.php"><label for="itemName[]">Item</label><input type="text" name="itemName[]"><label for="itemPhoto[]">Photo</label><input type="text" name="itemPhoto[]"><input type="hidden" name="itemId[]" value=""><input type="hidden" name="itemParent[]" value="<?=$_GET["room"]?>"><div class="saveIcon" style="display: none; color: green;">SAVED!</div><div class="save">Save Item</div></form>').fadeIn(500).appendTo('.addItem');
    });
});

基本上,我把重复的逻辑放在一个更通用的函数中。