2

例如,有人正在写一篇文章,但不小心关闭了浏览器。是否有可能保存他写的所有内容?

像这样的东西:

onExit -> 获取用户填写的所有信息 -> 将信息保存在数据库中的 AJAX 请求。

或者

是否只能通过每 x 秒抢先保存?

4

3 回答 3

2

我的公司通过运行 ajax 查询以每 5 秒保存一次来做到这一点,但您应该考虑localStorage在客户端上进行保存,onunload用于保存并稍后恢复。

我制作了一个html5 记事本,它存储到localStorage每个onchange事件和每 500 毫秒并onbeforeunload保存一个字段,但它很容易修改,这是(基本)代码:

<textarea placeholder="Type here, see it here..."  id="notepad"></textarea>
<script>
    var n = document.getElementById("notepad");
    /* save */
    var s = function(){localStorage.setItem("notepad", n.value);}
    /* retrieve (only on page load) */
    if(window.localStorage){ n.value = localStorage.getItem("notepad");}
    /* autosave onchange and every 500ms and when you close the window */
    n.onchange = s();
    setInterval( s, 500);
    window.onunload = s();
</script>

如果您在该页面上查看源代码,您还会发现一个用于支持旧浏览器的polyfilllocalStorage ,但应该可以在 IE8+ 中使用

我不相信客户端onbeforeunload单独完成一个 ajax 调用,但我真的不知道该功能如何在顶级浏览器中工作。

于 2012-06-04T13:20:15.790 回答
1

我可能会使用本地存储和 ajax 的组合,并且我会使用延迟的 setTimeout,以便在一段时间不活动后发出 ajax 请求。

因此,例如,您可以将 ajax 刷新绑定到要保存的项目的事件:

$("#fieldToSave").bind("keyup",(function()
        {
            var timeoutId = null;
            var previous = "";
            return function(e)
            {
                var that = this;

                if ($(that).val() != previous)
                {
                    previous = $(that).val();
                    clearTimeout(timeoutId);
                    timeoutId = setTimeout(function()
                    {
                        ajaxRefresh();

                        if(window.localStorage)
                        {
                            localStorage.setItem("notepad", that.value);} 
                        }
                    }, 300);
                }
            };
        })());

这种方法使用 ajax 和本地存储来保持“fieldToSave”的值,此外它不会一遍又一遍地持续保存。例如,它的作用是在 keyup 上,它将执行保存,但每 300 毫秒仅执行一次。因此,如果用户连续输入,直到用户停止 300 毫秒后才会保存。这真的可以绑定到您想要的任何事件。

您决定在页面加载时如何/在何处加载内容由您决定。

希望这可以帮助。

于 2012-06-04T13:59:14.333 回答
0

答案:是否只能通过每 x 秒抢先保存?在下面

您需要在一定时间内调用 ajax 函数,就像我在 blelow 代码中所做的那样...... settime out 函数每 1000 秒后调用 ajaxRefresh 函数......

function onLoad() {
    setTimeout(ajaxRefresh, 1000);
} 

function ajaxRefresh()
{
    //ajax code to post data 
    $.ajax({
                type: "GET",        //GET or POST or PUT or DELETE verb
                url: ajaxUrl,       // Location of the service
                data: "",       //Data sent to server
                contentType: "",        // content type sent to server
                dataType: "json",   //Expected data format from server
                processdata: true,  //True or False
                success: function (json) {//On Successful service call
                    var result = json.name;
                    $("#dvAjax").html(result);
                },
                error: function() { alert("err")};  // When Service call fails
            });

    setTimeout(ajaxRefresh, 1000);
}
于 2012-06-04T13:21:09.800 回答