dqgg25493 2015-03-13 06:40
浏览 46
已采纳

如何检查服务器是否返回undefined然后忽略它

I am sent many dynamic post ids from a page and a php server side page(server.php) make a query with those id to find out newly added data in mysql.

If it not found any newly added data in mysql, it's return a undefined value. So as per my script, It's append a undefined one after one at a time interval.

So how can I check, if php query cannot found anything in sql then exit and not return anything?

I tried this in my php if(mysqli_num_rows($res)) { //do something } but it's also display undefined.

my javascript:

var CID = []; // Get all dynamic ids of posts (works well)
$('div[data-post-id]').each(function(i){
CID[i] = $(this).data('post-id');
});

function addrep(type, msg){
CID.forEach(function(id){
    $("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul><div class='cdomment_text'>"+ msg.detail +"</ul></div>");
});
}

function waitForRep(){
    $.ajax({
        type: "GET",
        url: "server.php",
        cache: false,
        data: {CID : CID},
        timeout:15000, 
        success: function(data){ 
            addrep("postreply", data);
            setTimeout(waitForRep, 15000 );
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            setTimeout(waitForRep, 15000); }
    });
}

$(document).ready(function(){
    waitForRep();
});

server.php

while (true) {
    if($_REQUEST['CID']){  //cid got all dynamic post id as: 1,2,3,4 etc.
      foreach($_REQUEST['CID'] as $key => $value){

        $datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
        $res = mysqli_query($dbh,"SELECT * FROM reply WHERE qazi_id=".$_REQUEST['tutid']."  AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
    $data = array();
        while($rows =  mysqli_fetch_assoc($res)){

          $data[]=$rows;

          $data['id'] = $rows['id']; 
          $data['qazi_id'] = $rows['qazi_id'];
          $data['username'] = $rows['username'];
          $data['description'] = $rows['description'];
          $data['date'] = $rows['date'];
          //etc. all
             $id = $rows['id'];
             $qazi_id = $rows['qazi_id'];
             $username = $rows['username'];
             $description = $rows['description'];
             //etc. all
          } //foreach close
      } //foreach close

          if ($description=="") {$detail .= '';}
            else {$detail .=''.$description.'';}
          $data['detail'] = $detail;
          // do others something more

           if (!empty($data)) {
              echo json_encode($data);
              flush();
              exit(0);
           }

    } //request close
    sleep(5);
} //while close
  • 写回答

1条回答 默认 最新

  • dtv11049 2015-03-13 06:56
    关注

    I tried this in my php if(mysqli_num_rows($res)) { //do something } but it's also display undefined.

    I guess that should be because you are calling this php code every 15000 ms via ajax with a setTimeout.

    So instead stopping it there you can just ignore it with your js code in addrep() function.

        function addrep(type, msg) {
          CID.forEach(function(id) {
            if (msg.id !== undefined && msg.detail !== undefined) { // <--check undefined here
              $("#newreply" + id).append("<div class='" + type + "" + msg.id + "'>"+
                                         "<ul><div class='cdomment_text'>" + msg.detail +
                                         "</ul></div>");
            }
          });
        }
    

    Or other option is to make use of clearTimeout() when you get undefined.

    var timer; // declare the timer here
    var CID = []; // Get all dynamic ids of posts (works well)
    $('div[data-post-id]').each(function(i) {
      CID[i] = $(this).data('post-id');
    });
    
    function addrep(type, msg) {
      CID.forEach(function(id) {
        if(msg.id === undefined || msg.details === undefined){
            clearTimeout(timer); // cleartimeout timer
        }else{
            $("#newreply" + id).append("<div class='" + type + "" + msg.id + "'><ul><div class='cdomment_text'>" + msg.detail + "</ul></div>");
        }
      });
    }
    
    function waitForRep() {
      $.ajax({
        type: "GET",
        url: "server.php",
        cache: false,
        data: {
          CID: CID
        },
        timeout: 15000,
        success: function(data) {
          addrep("postreply", data);
          timer = setTimeout(waitForRep, 15000); // assign the settimeout to timer
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          setTimeout(waitForRep, 15000);
        }
      });
    }
    
    $(document).ready(function() {
      waitForRep();
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题