jQuery自动保存不能正常工作

时间:2013-07-09 21:37:50

标签: php jquery ajax autosave

我在下面写了几个脚本,它们分别很好地工作,但是它们并没有按照它们应该的方式工作。让我发布代码然后解释问题:

自动保存功能:

<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并将该数据放入隐藏字段中,以便在需要插入查询或需要更新查询时(当返回的id存在时),php脚本可以解决。还有一个名为addForm的可点击div,然后在另一个表单下面添加另一个表单集,再次点击它的保存按钮时,该表单将在数据库中保存/更新。当我在我的代码中触发自动保存时,自动保存字面上采用所有表单并将它们保存为新条目,但不返回id /更新隐藏字段以触发更新序列。你能否对此有所了解?这真让我烦恼。我尽力解释这个,对不起,这太久了。这有点复杂!哈哈

1 个答案:

答案 0 :(得分:1)

我建议对代码的组织进行一些更改,然后更容易识别错误。

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

基本上我采用了重复的逻辑并将其放入更通用的函数中。