为什么Ajax只适用于最新的帖子?

时间:2016-05-11 17:29:47

标签: php ajax

我想使用Ajax调用PHP页面而不刷新。

这是我的代码

<?php 


global $db;
$cmd = "SELECT * FROM posts order by date desc";
$result = mysqli_query($db,$cmd);
while ($row = mysqli_fetch_assoc($result)){
    $post_txt = $row['text'];
    $post_image = $row['image'];
    $postid = $row['postid'];
    $date = $row['date'];
    $userid = $row['userid'];

    $new_date=time_elapsed_string($date);


    ?>


    <?php
    global $db;
    $sql = "SELECT * FROM user WHERE id = '$userid'";
    $result2 = mysqli_query($db,$sql);
    while($row2 = mysqli_fetch_assoc($result2)){
        $acountname = $row2['name'];
        $acountlast_name = $row2['lastname'];
    } 
    ?>


<?php



echo"
<div id='postShare'>

    <div class='col-xs-7' id='listPost'>
                <div class='list-group'>    

            <input type='hidden' value='$userid' id='user_id_input_hidden'>     
            <li class=list-group-item text-center'><span class='pull-right'><p><a href='profile.php' id='prof_btn'>$acountname  $acountlast_name</a></p></span>&nbsp;
            <span class='pull-left'><p>$new_date</p></span>
            <hr>
            <center><h5 id='show_post_title'>$post_txt</h5></center> <hr>";?>

我想用Ajax加载profile.php

$(document).ready(function(){
    $('#prof_btn').click(function(){

        var userid = $('#user_id_input_hidden').val();
        var dataString = 'userid=' + userid;

        $.ajax({

          url:'profile.php',
          type:'POST',
          data:dataString,
          success:function(prof){
            $('html').empty();
            $('html').append(prof);
          }

        });

        return false;
    });
});

但它仅适用于echo中的最新帖子,不适用于任何帖子。有什么问题?

3 个答案:

答案 0 :(得分:2)

加载配置文件时,您添加事件的#prof_btn元素已消失,并被没有绑定任何事件的新元素替换。

您有两种选择:

  1. 手动重新应用事件。
  2. 使用event delegation将事件委派给未被替换的父元素。

答案 1 :(得分:1)

在循环内移动回声

global $db;
$sql = "SELECT * FROM user WHERE id = '$userid'";
$result2 = mysqli_query($db, $sql);
while ($row2 = mysqli_fetch_assoc($result2)) {
    $acountname = $row2['name'];
    $acountlast_name = $row2['lastname'];
    echo"
        <div id='postShare'>
        <div class='col-xs-7' id='listPost'>
        <div class='list-group'>    
        <input type='hidden' value='$userid' id='user_id_input_hidden'>     
        <li class=list-group-item text-center'><span class='pull-right'><p><a href='profile.php' id='prof_btn'>$acountname  $acountlast_name</a></p></span>&nbsp;
        <span class='pull-left'><p>$new_date</p></span>
        <hr>
        <center><h5 id='show_post_title'>$post_txt</h5></center> <hr> 
        ";
} 

答案 2 :(得分:1)

删除最后一个括号:

while($row2 = mysqli_fetch_assoc($result2)){
    $acountname = $row2['name'];
    $acountlast_name = $row2['lastname'];
---> } 

并在此结束:

<center><h5 id='show_post_title'>$post_txt</h5></center> <hr>";
--> }?>