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

时间:2015-03-13 06:40:51

标签: javascript php jquery

我从一个页面发送了许多动态post id,并且php服务器端页面(server.php)使用这些id进行查询,以在mysql中找出新添加的数据

如果在mysql中未找到任何新添加的数据,则返回undefined值。因此,根据我的脚本,它会以一个时间间隔逐个追加undefined

那我怎么检查,如果php查询在sql中找不到任何东西然后退出而不返回任何内容?

我在我的php if(mysqli_num_rows($res)) { //do something }中尝试了这个,但它也显示未定义。

我的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 个答案:

答案 0 :(得分:1)

我在我的php if(mysqli_num_rows($res)) { //do something }中尝试了这个,但它也显示了undefined

我想这应该是因为你通过ajax 15000setTimeout ms调用这个php代码。

因此,在那里停止它,您可以使用addrep()函数中的js代码忽略它。

    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>");
        }
      });
    }

或其他选项是在获得clearTimeout()时使用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();
});