使用ajax php加载更多

时间:2016-06-07 10:51:11

标签: javascript php ajax

你好在这里我有一个问题,加载更多的ajax都是okey但是当没有 要从数据库显示的数据显示此错误:http://i.stack.imgur.com/6158Y.png

的index.php

<div id="show_here">
<div id="hide_here" onclick="show_more_posts(<?php echo $post['id']; ?>);">Show More Posts</div>
</div>

main.js

// Load more post
function show_more_posts(post_id)
{
    var ID = post_id;
    $.ajax({
    type: "POST",
    url: "ajax/ajax_more.php",
    data: "lastmsg="+ ID, 
    cache: false,
    success: function(html){
        $("#show_here").append(html);
        $("#hide_here").remove();
    }
    });
    return false;
}

ajax_more.php

 <?php
include("../config.php");

$lastmsg = $_POST['lastmsg'];
$result = mysqli_query($Connection, "select * from posts where id<'$lastmsg' order by id desc limit 10");

while($row = mysqli_fetch_array($result))
{
    $msg_id=$row['id'];
    $message=$row['text']; ?>

    <li> <?php echo $message; ?> </li> <?php
}
?>

<div id="show_here">
    <div id="hide_here" onclick="show_more_posts(<?php echo $msg_id; ?>);">Show More Posts</div>
</div>

4 个答案:

答案 0 :(得分:0)

你只需要这样做

<div id="show_here">
<?php
if(isset($post['id'])) {
?>
    <div id="hide_here" onclick="show_more_posts(<?php echo $post['id']; ?>);">Show More Posts</div>
<?php
}else{
?>
<div id="hide_here">No More Posts to show !!!!</div>
<?php
}
?>
</div>

试试这个,它可能对你有帮助

答案 1 :(得分:0)

你可以这样使用。然后你不会得到错误。

<?php
if(isset($msg_id)) {
?>
<div id="show_here">
    <div id="hide_here" onclick="show_more_posts(<?php echo $msg_id; ?>);">Show More Posts</div>
</div>
<?php
}
?>

答案 2 :(得分:0)

在你的ajax_more.php文件中,你必须在while之前将$msg_id设置为$lastmsg

<?php
include("../config.php");

$lastmsg = $_POST['lastmsg'];
$result = mysqli_query($Connection, "select * from posts where id<'$lastmsg' order by id desc limit 10");

$msg_id = $lastmsg;
while($row = mysqli_fetch_array($result))
{
    $msg_id=$row['id'];
    $message=$row['text']; ?>

    <li> <?php echo $message; ?> </li> <?php
}
?>

    <div id="hide_here" onclick="show_more_posts(<?php echo $msg_id; ?>);">Show More Posts</div>

因此,即使您的查询没有返回数据(没有新消息),该变量也具有正确的值。

相反,如果您希望在某些时候加载更多帖子,则必须使用Kaja Mydeen提供的解决方案:

<?php
include("../config.php");

$lastmsg = $_POST['lastmsg'];
$result = mysqli_query($Connection, "select * from posts where id<'$lastmsg' order by id desc limit 10");

while($row = mysqli_fetch_array($result))
{
    $msg_id=$row['id'];
    $message=$row['text']; ?>

    <li> <?php echo $message; ?> </li> <?php
}
?>

<?php if(isset($msg_id)) { ?>
    <div id="hide_here" onclick="show_more_posts(<?php echo $msg_id; ?>);">Show More Posts</div>
<?php } ?>

此外,您的代码有些奇怪:您继续使用div添加id="show_here"

答案 3 :(得分:0)

我认为在通过while循环获取数据之前,您应该检查总受影响的行,例如

$totrows = mysql_num_rows($result);
if($totrows > 0){
  //your while loop for fetch data
}else{
  //return something else
}