AJAX在特定时间检查和更新。

时间:2016-05-06 16:35:52

标签: ajax

我是Ajax的新手,我遇到了一个问题。我有一个html表单和一个数据库,输入是一个整数。如果输入改变,我想每5秒检查一次。如果是这样,我想更新数据库。如果不是,我希望它在5秒内再次检查。我如何在AJAX中做到这一点?

2 个答案:

答案 0 :(得分:0)

使用setInterval功能进行检查

 setInterval(function(){
    var value=$("#your_id").val();//textbox value
    $.ajax({
        url: "ajax.php",
        type: "get", //send it through get method
        data:{value: value },
        success: function(response) {
            //Do Something
            //alert(response);
        },
        error: function(xhr) {
            //Do Something to handle error
        }
    });
}, 5000);

在ajax.php中检查该值

if(isset($_GET['value'])){
$value=$_GET['value'];
//select your old value from database suppose it as $old_value
if($value!=$old_value){
    //update your table using $value
 }
}

答案 1 :(得分:0)

使用全局js变量

var gblPreviousTxtBoxValue = $('#txtboxid').val();

使用setInterval函数每5秒调用一次函数

setInterval(function(){
    var currentTxtBoxValue =$("#your_id").val();

    if(gblPreviousTxtBoxValue != currentTxtBoxValue) //check if current and previous textbox values are not equal
    {
     $.ajax({
        url: "yoururl",
        type: "post",
        data: { "textboxname": currentTxtBoxValue },
        success: function(response) {
            //Code
            },
        error: function(xhr) {
            //Do Something to handle error
        }
      });
     }
     gblPreviousTxtBoxValue = currentTxtBoxValue; //assign current value
    }, 5000);