如果有新的数据,则停止重复插入

If new data else stop insert over and over

本文关键字:插入 数据 如果      更新时间:2023-09-26

为了保持简单,我只是想知道如何对ajax和if else语句进行操作,以便在发现新数据时一次打印出来,而不是一次又一次地打印相同的数据。我怎么可能存储最后一个id作为一个变量来重用它时搜索更多的新记录?

有人向我提到,我也可以保存新的通知的想法作为返回,所以当ajax重启时,它使用它来找到下一个新的结果集。

有谁知道如何实现这些吗?

<script type="text/javascript">
setInterval(function(){
var time = new Date().getTime();
  var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&time="+time ,   
dataType:"json",
cache: false,
success: function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div  id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text"><a href="'+response['notification_id']+'">'+response['notification_content']+' </a><br />'+response['notification_time']+'</div></nr>');
 $("#mes").html(''+ response.num + '');
}
}
});
},20000);
</script>

关于存储最后一个id,您可以使用:

window.localStorage.setItem('key', 'value');

当你想再次获得它时,你应该使用:

var lastId = window.localStorage.getItem ('key'); 

关于重复的问题,您应该有一个内部存储器来处理接收到的数据。可以使用数组作为存储,也可以将数组存储在本地。

一旦你处理了这个数据存储,你可以应用这样的东西来验证你的数据没有重复:

var dataHandler = function (response){
   var isDuplicate = false, storedData = window.localStorage.getItem ('key');
   for (var i = 0; i < storedData.length; i++) {
     if(storedData[i].indexOf(response) > -1){
        isDuplicate = true;
     }
   }
   if(!isDuplicate){
     storedData.push(response);
   }
}; 
var printer = function(response){
   if(response.num){
      $("#notif_actual_text-"+notification_id).prepend('<div  id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text"><a href="'+response['notification_id']+'">'+response['notification_content']+' </a><br />'+response['notification_time']+'</div></nr>');
      $("#mes").html(''+ response.num + '');
    }
};

更新
var notification_id = window.localStorage.getItem ('lastId'); 
    $.ajax({
    type: "GET",
    url: "viewajax.php?notification_id="+notification_id+"&time="+time ,   
    dataType:"json",
    cache: false,
    success: function(response){
    if(response){
    dataHandler(response);
    if(response.num){
       window.localStorage.setItem('lastId', response.num);
    }
    });
    },20000);