javascript - 如何在不点击或提交的情况下实时更新数据

标签 javascript jquery ajax

我需要更新表中的数据,而不需要发送单击或提交操作。例如,当我更改输入值时,我想将这些更改实时保存在数据库中。

我的问题是,我如何比较表单是否有变化? 我读了这篇文章,Submitting data without clicking a submit button ,但在这里,该函数每 5 秒执行一次,我需要保存的只是有更改。

HTML

 <form id="formos" method="">
 Status:<input type="text" class="form-control uppercase" form="">
 </form>

JS

$(window).bind('beforeunload', function(e){
    if($('#formos').serialize()!=$('#formos').data('serialize'))return true;
    else e=null; // i.e; if form state change show box not.
});

最佳答案

我的做法是这样的。我通过 ajax 通过击键发送数据。但我设置了 300 毫秒的超时,这样只有当他们停止输入时,它才不会在每次击键时发送。

然后我检查服务器端是否有更改,如果没有,我什么都不做,是否已经有我更新的条目,如果没有我插入的条目。简单。

如果您在使用代码时遇到问题,我可以提供一些。

HTML:

<input type="text" id="test_1" />
<input type="text" id="test_2" />

JS:

$(function(){
    $('input[type=text]').keyup(function(){
        var elem = $(this);
        clearTimeout($(this).data('timer'));
        $(this).data('timer', setTimeout(function(){
            sendValue(elem.attr('id'), elem.val());
        }, 300));
    });
    $('input[type=text]').change(function(){
        sendValue($(this).attr('id'), $(this).val());
    });
});

function sendValue(key, value) {
    $.post('path/to/script.php', {key: key, value: value}, function(data, result){
        if(result == 'success') {
            console.log('Data was sent');
        } else {
            console.log('AJAX post failed');
        }
    });
}

PHP:

$key = $_POST['key']; //just remember never to just receive input from a user, first check if it is something valid and not something trying to hack you
$value = $_POST['value'];
//then check if there is a difference of value to what you had
//insert or update in your db accordingly
die(); //die if you are using a controller within a framework, if you do not it will send back all the other stuff with it

我希望这会有所帮助。

关于javascript - 如何在不点击或提交的情况下实时更新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37765166/

相关文章:

javascript - 删除鼠标悬停时的 Css 类

javascript - 通过 JavaScript 更新输入字段值后无法清除验证消息

javascript - 使用 ajax 调用循环遍历函数

javascript - 使用 splice 和 for 循环删除原始数组

Javascript - 理解 Object.create 和 Object.call(this)

c# - 如何将参数传递给ajax调用

javascript - 使用 REST API 在 SharePoint Online 中外部共享文件夹

jquery - 启用服务器端处理时出现列宽问题

jquery - 使用 jQuery 将 JSON 对象发送到新页面

jquery - 在列表中过滤 Jquery 中的结果