在键入暂停期间自动将输入框保存到数据库

Autosave input box's to database during pause in typing?

本文关键字:输入 保存 数据库 暂停      更新时间:2023-09-26

我的网站上有一个大表单,我希望能够在用户填写时自动保存到数据库中。几乎与输入文档时的谷歌云端硬盘的工作方式相同。

我试图不让一个每 X 秒运行一次的函数,而是一个在用户打字休息时运行的函数。因此,如果用户在 1 小时内没有键入内容,但仍在页面上,则不会继续推送保存请求。

这就是我到目前为止所拥有的一切,这是一个基本的javascript表单提交。

$("#page1Form").submit(function(event){
  event.preventDefault();  
  $changesSaved.text("Saving...");
  var url = "/backend/forms/page1-POST.php";
        $.ajax({
         type: "POST",
         url: url,
         data: $("#page1Form").serialize(),
         success: function(data) { $changesSaved.text(data); }
        });
  return false;
  });

取消文本区域更改。

演示:jsFiddle

将 ajax 调用放在 saveToDB() 函数中。这些事件名称('input propertychange change')将在任何表单元素更改(如单选按钮,输入等)时触发。

var timeoutId;
$('#the-textarea').on('input propertychange change', function() {
    console.log('Textarea Change');
    clearTimeout(timeoutId);
    timeoutId = setTimeout(function() {
        // Runs 1 second (1000 ms) after the last change    
        saveToDB();
    }, 1000);
});
function saveToDB()
{
    console.log('Saving to the db');    
}

这是一个完整的演示,向您展示如何取消完整表单的反弹并使用 ajax 发送数据,然后返回状态(保存、已保存等)。

演示完整形式和ajax:jsFiddle

我知道

这个问题很老,但我想包含一个我最喜欢的代码。我在这里找到了它:http://codetunnel.io/how-to-implement-autosave-in-your-web-app/

这是代码:

var $status = $('#status'),
    $commentBox = $('#commentBox'),
    timeoutId;
$commentBox.keypress(function () {
    $status.attr('class', 'pending').text('changes pending');
    // If a timer was already started, clear it.
    if (timeoutId) clearTimeout(timeoutId);
    // Set timer that will save comment when it fires.
    timeoutId = setTimeout(function () {
        // Make ajax call to save data.
        $status.attr('class', 'saved').text('changes saved');
    }, 750);
});

它在用户停止写入超过 750 毫秒后保存。

它还具有一个状态,让用户知道更改是否已保存。

试试西西弗斯.js https://github.com/simsalabim/sisyphus。它将表单数据保留在浏览器的本地存储中,并且对选项卡关闭、浏览器崩溃等具有鲁棒性......