如何只每隔几秒获取一次变量并更新它

时间:2021-10-09 05:27:32

I have a form where maintenance employees at my company fill out at the end of the day to describe what they did that day. Some fill it out on their phones sometimes. They complained that if they got a call or text they would loose their log they had typed up.

我有一个表格,我公司的维护人员在一天结束时填写,以描述他们当天所做的事情。有些人有时会在手机上填写。他们抱怨说,如果他们接到电话或短信,他们就会丢失他们输入的日志。

So what I did is store the form values into PHP SESSION variables via AJAX and echo out the variable if the form is reloaded as long as they're signed in.

所以我所做的是通过AJAX将表单值存储到PHP SESSION变量中,并在表单重新加载时回显变量,只要它们已经登录即可。

This is one of input fields:

这是输入字段之一:

<textarea class="form-control" name="8to10" id="d8to10" placeholder="8 to 10 am" rows="8">
  <?php if(isset($_SESSION['d8to10'])){echo htmlspecialchars($_SESSION['d8to10'], ENT_QUOTES);} ?>
</textarea>
<span id="saved1"><span>

This is the corresponding Javascript that grabs the field's value and sends it through AJAX to get store into the SESSION variable.

这是相应的Javascript,它抓取字段的值并通过AJAX发送它以存储到SESSION变量中。

$('#d8to10').on("keyup", function(){

    var d8to10 = $(this).val();
    $('#saved1').css('display', 'none');

    d8to10 = encodeURIComponent(d8to10);
    //console.log(d8to10);

    var ajaxRequest;
    clearTimeout(ajaxRequest);
        ajaxRequest = setTimeout(function() {

            $.ajax({
                type: 'post',
                url: 'Includes/dailyLogCacheLog.php',
                data: 'd8to10=' + d8to10,
                success: function(r) {
                    $('#saved1').css('display', 'inline');
                    $('#saved1').html('<p>Saved</p>');
                }
            });
        }, 3000, d8to10);

});

So what I want to do now and can't figure out how to do right is to only grab the variable every 5 or 10 seconds as they type and save it in that time frame. This is because now the AJAX is being called after every letter typed up and they're complaining that the saved message is blinking too much.

所以我现在想要做的并且无法弄清楚如何做正确的事情就是在键入时每隔5或10秒抓取一次变量并将其保存在该时间范围内。这是因为现在在每个输入的字母后调用AJAX,他们抱怨保存的消息闪烁太多。

Anyone know a way to do this?

有人知道这样做的方法吗?

3 个解决方案

#1


2  

Something like this might do the trick, this basically only executes the ajax about three seconds after the user stops typing. If you want to have multiple calls while the user types, you can remove the clearTimeout and abort calls.

这样的事情可能会成功,这基本上只在用户停止输入后大约三秒钟执行ajax。如果要在用户键入时进行多次呼叫,可以删除clearTimeout并中止呼叫。

var timeout_d8to10;
var xhr_d8to10;
$('#d8to10').on("keyup", function(){
    var $this = $(this);
    if (timeout_d8to10) {
        clearTimeout(timeout_d8to10);
    }
    if ( xhr_d8to10) {
        xhr_d8to10.abort();
    }
    timeout_d8to10 = setTimeout( function () {
        var d8to10 = $this.val();
        d8to10 = encodeURIComponent(d8to10);

        $('#saved1').css('display', 'none');
        xhr_d8to10 = $.ajax({
            type: 'post',
            url: 'Includes/dailyLogCacheLog.php',
            data: 'd8to10=' + d8to10,
            success: function(r) {
                $('#saved1').css('display', 'inline');
                $('#saved1').html('<p>Saved</p>');
            }
          });

    }, 3000);
});

#2


1  

Instead of firing your ajax on every keyup event when the document loads put your ajax call in a setInterval function that saves the contents of the textarea at the desired interval:

当文档加载时,不是在每个keyup事件上触发ajax而是将ajax调用放入setInterval函数中,该函数以所需的间隔保存textarea的内容:

var saveInterval; // to store ID in case you want to stop this later

$(document).ready(function() {
    // call saveContent every 3 seconds
    saveInterval = window.setInterval(saveContent, 3000);
});

function saveContent() {
    var d8to10 = $(this).val();
    $('#saved1').css('display', 'none');

    d8to10 = encodeURIComponent(d8to10);
    //console.log(d8to10);

    var ajaxRequest;

    ajaxRequest = function() {

        $.ajax({
            type: 'post',
            url: 'Includes/dailyLogCacheLog.php',
            data: 'd8to10=' + d8to10,
            success: function(r) {
                $('#saved1').css('display', 'inline');
                $('#saved1').html('<p>Saved</p>');
            }
        });
    }, d8to10);
};

#3


1  

If your intent was to have the Auto-Save feature of the field, similar to how gmail would save drafts, then I believe you are going to need a separate ajax call. As bwegs suggested, use a setInterval. If you absolutely must keep the keyup call, then just add something like this below it

如果您打算使用该字段的自动保存功能,类似于gmail如何保存草稿,那么我相信您将需要单独的ajax调用。正如bwegs所建议的那样,使用setInterval。如果你绝对必须保持键盘调用,那么只需在它下面添加这样的东西

function getFreshValue() {
  var newVal;

  $.get('someUrl')
    .then(function(data) {
      // Logic that handles inserting the new value
      // and / or making sure there is a valid value first
    });
}

setInterval(getFreshValue, 7500) // 7.5 second interval

EDIT: I really don't think there is a way to get around this without multiple calls. Unless you do it on an interval of keystrokes (every 10-15 keypresses for example).

编辑:我真的不认为没有多次通话就有办法解决这个问题。除非你按键击间隔(例如每10-15次按键)。

Hoping someone else can do better?

希望别人可以做得更好?

#1


2  

Something like this might do the trick, this basically only executes the ajax about three seconds after the user stops typing. If you want to have multiple calls while the user types, you can remove the clearTimeout and abort calls.

这样的事情可能会成功,这基本上只在用户停止输入后大约三秒钟执行ajax。如果要在用户键入时进行多次呼叫,可以删除clearTimeout并中止呼叫。

var timeout_d8to10;
var xhr_d8to10;
$('#d8to10').on("keyup", function(){
    var $this = $(this);
    if (timeout_d8to10) {
        clearTimeout(timeout_d8to10);
    }
    if ( xhr_d8to10) {
        xhr_d8to10.abort();
    }
    timeout_d8to10 = setTimeout( function () {
        var d8to10 = $this.val();
        d8to10 = encodeURIComponent(d8to10);

        $('#saved1').css('display', 'none');
        xhr_d8to10 = $.ajax({
            type: 'post',
            url: 'Includes/dailyLogCacheLog.php',
            data: 'd8to10=' + d8to10,
            success: function(r) {
                $('#saved1').css('display', 'inline');
                $('#saved1').html('<p>Saved</p>');
            }
          });

    }, 3000);
});

#2


1  

Instead of firing your ajax on every keyup event when the document loads put your ajax call in a setInterval function that saves the contents of the textarea at the desired interval:

当文档加载时,不是在每个keyup事件上触发ajax而是将ajax调用放入setInterval函数中,该函数以所需的间隔保存textarea的内容:

var saveInterval; // to store ID in case you want to stop this later

$(document).ready(function() {
    // call saveContent every 3 seconds
    saveInterval = window.setInterval(saveContent, 3000);
});

function saveContent() {
    var d8to10 = $(this).val();
    $('#saved1').css('display', 'none');

    d8to10 = encodeURIComponent(d8to10);
    //console.log(d8to10);

    var ajaxRequest;

    ajaxRequest = function() {

        $.ajax({
            type: 'post',
            url: 'Includes/dailyLogCacheLog.php',
            data: 'd8to10=' + d8to10,
            success: function(r) {
                $('#saved1').css('display', 'inline');
                $('#saved1').html('<p>Saved</p>');
            }
        });
    }, d8to10);
};

#3


1  

If your intent was to have the Auto-Save feature of the field, similar to how gmail would save drafts, then I believe you are going to need a separate ajax call. As bwegs suggested, use a setInterval. If you absolutely must keep the keyup call, then just add something like this below it

如果您打算使用该字段的自动保存功能,类似于gmail如何保存草稿,那么我相信您将需要单独的ajax调用。正如bwegs所建议的那样,使用setInterval。如果你绝对必须保持键盘调用,那么只需在它下面添加这样的东西

function getFreshValue() {
  var newVal;

  $.get('someUrl')
    .then(function(data) {
      // Logic that handles inserting the new value
      // and / or making sure there is a valid value first
    });
}

setInterval(getFreshValue, 7500) // 7.5 second interval

EDIT: I really don't think there is a way to get around this without multiple calls. Unless you do it on an interval of keystrokes (every 10-15 keypresses for example).

编辑:我真的不认为没有多次通话就有办法解决这个问题。除非你按键击间隔(例如每10-15次按键)。

Hoping someone else can do better?

希望别人可以做得更好?