我想使用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>
<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
中的最新帖子,不适用于任何帖子。有什么问题?
答案 0 :(得分:2)
加载配置文件时,您添加事件的#prof_btn
元素已消失,并被没有绑定任何事件的新元素替换。
您有两种选择:
答案 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>
<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>";
--> }?>