我正在尝试通过ajax拉取mysql表的最新条目,并将其显示为div中的html内容。我的ajax和php功能正常,我唯一的问题是我想查询新条目并在循环内的某个时间间隔内将结果堆叠在一起,而我遇到了两个问题:使数据的行为像正常情况一样javascript字符串,并使循环仅返回唯一条目。

update.php文件

$con=mysqli_connect("mydbhost.com","username","password","database_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM conversations");
$j = 0;
while($row = mysqli_fetch_array($result))
{
$carray[j] =   $row['comment'];
$j++;
}
$comment = (array_pop($carray));
echo $comment;
echo "<br>";
mysqli_close($con);


jQuery Ajax请求循环:

$(document).ready(function(e){
  var comment;
  function commentLoop() {
    comment = $('#testdiv').load('update.php');
    $('#testdiv').append(comment);
    setTimeout(commentLoop, 6000);
  }
  commentLoop();

  $(document).focus();
});

最佳答案

这将对表中的注释进行计数,并选择最后输入的注释,然后仅在接收到的计数低于表中注释的计数时,将它们作为json数据传递给ajax:

PHP:

if(isset($_GET['data']))
{
    $con        = new mysqli('host', 'user', 'password', 'database');
    $init_count = $_GET['data'];
    $stmt1      = "SELECT COUNT(*) AS count FROM conversations";
    $stmt2      = "SELECT comment FROM conversations ORDER BY date_column DESC LIMIT 1";

    $total = $con->prepare($stmt1);
    $total->execute();
    $total->bind_result($count);
    $total->fetch();
    $total->close();

    if( ($init_count != '') && ($init_count < $count) )
    {
        $lastComment = $con->prepare($stmt2);
        $lastComment->execute();
        $result = $lastComment->get_result();
        $row    = $result->fetch_assoc();
        $lastComment->close();

        $data = array(
                 'comment' => $row['comment'],
                 'count'   => $count
                 );
    }

    elseif($init_count == '')
    {
        $data = array(
        'comment' => '',
        'count'   => $count
        );
    }
    $pdo->close();
    echo json_encode($data);
}


HTML:

<input type="hidden" id="count" value="" />


JQUERY:

$(document).ready(function(e){

    function getComment(){
        var count = $('#test').val();
        $.ajax({
                type: 'get',
                url: 'update.php?data=' + count,
                dataType: 'json',
                success: function(data)
            {
            $('#count').val(data.count);
            if(data.comment) !=  $('#testdiv').html(data.comment);
            }
        });
    }
    getComment();
    setInterval(getComment, 6000);

});

09-25 18:14
查看更多