我有一个while循环,用于获取和echos状态更新。我试图在while循环中回显一个"REPOST"链接,以便它附加到任何状态更新(位于其下方),并在单击时将ID传递到外部.php文件。这个链接是jquery+ajax。
<script type="text/javascript">
$(document).on('click', 'a[id^=repost]', function(){
var thePostID = $(this).prop('id').split('-')[1];
//this now has the id of the $row['id'] we declared earlier.
$.ajax({
url: 'reposthandler.php',
type: 'POST',
data: {'id' : thePostID},
success: function(data){
}
});
});
</script>
<?php
include ('time.php');
$query = "SELECT poster, posterpic, category, type, date, id, follow.beingfollowed
FROM usergen LEFT JOIN follow ON follow.beingfollowed = usergen.poster WHERE
follow.iwannafollow
= '*".$loggedin."' ORDER BY usergen.date DESC ";
$result = mysql_query($query) or die(mysql_error()) ;
$rows = array();
while($row = mysql_fetch_array($result)) {
$row['ago'] = ago($row['date']);
$rows[] = $row;
echo '<br />';
echo '<img src="' . $row['posterpic'] . '" width="40px" height="50px">';
echo '<font color="red" size=2px><i>';
echo '<a>'.$row['poster'].'</a></i></font>';
echo '<br />';
echo $row['category'] . ' for ' . $row['type'] . ' (' . $row['ago'] . ')';
echo '<a href="#" id="repost-',$row['id'],'">REPOST</a>';
echo '<br /><br /><HR size="4" width="auto" color="white">';
}
echo '</div>';
?>
链接是死的,没有链接到任何东西。为什么会这样?我需要在"成功:函数(数据)"下面添加一些内容吗?
Simply add an element to the loop for the button.
echo '<a href="#" id="repost-',$row['id'],'"> Repost This </a>';
将click函数绑定到静态父元素。
$(document).on('click', 'a[id^=repost]', function(){
var thePostID = $(this).prop('id').split('-')[1];
//this now has the id of the $row['id'] we declared earlier.
$.ajax({
url: 'path/to/my/controller.ext?postID='+thePostID,
type: 'POST',
success: function(){
//do whatever with the response.
}
});
});
现在,您将收到要转发的帖子的ID,您可以在后端php文件中随意处理它。