[英]How to tell PHP which comments to show under the article with AJAX?
I am building a news page for my website but I'm stuck displaying the right comments with ajax...我正在为我的网站构建一个新闻页面,但我无法使用 ajax 显示正确的评论...
commentsLoad.php评论加载.php
<?php
include('config.php');
$newsid = $_GET['newsid'];
$comments=array();
$commentsQuery = "SELECT * FROM comments
where fk_news like ".$newsid;
$result = $conn->query($commentsQuery);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
$comments[]=array('id' => $row['id'], 'name' => $row['cnick'], 'text' => $row['ctext'], 'date' => $row['cdate']);
}
}
//header('Content-type: application/json');
echo json_encode($comments);
exit;
?>
I dont know how to pass the right 'NEWSID'.我不知道如何传递正确的“NEWSID”。
Website picture: http://prntscr.com/8nwy8k网站图片: http : //prntscr.com/8nwy8k
How I want to pass that ID to the SQL Query我想如何将该 ID 传递给 SQL 查询
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
data:{newsid:'1'},
success: function(comments){
//console.log(komentarji);
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
So right now if I change the line data:{newsid:'1 or 2 or 3...'} I get the comments I want, but I dont know how to get that ID into a variable.所以现在,如果我更改行数据:{newsid:'1 or 2 or 3...'}我会得到我想要的评论,但我不知道如何将该 ID 放入变量中。
You can use onClick event for this.您可以为此使用 onClick 事件。
Explanation:解释:
Comment
link will look as follows Comment
链接将如下所示
<a href="javascript:void(0)" onClick="getComments('<?php echo $YOUR_ARTICLE_ ID?>')">Comments</a>
Then you can have a fucntion in your JQuery code to pass it to PHP file.然后你可以在你的 JQuery 代码中有一个功能来将它传递给 PHP 文件。
function getComments(article_id)
{
var artid = article_id;
$.ajax({
type: 'POST',
url: commentsUrl,
dataType: "json",
data:{newsid: artid},
success: function(comments){
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
}
Try set onclick function in the comment link.尝试在评论链接中设置 onclick 功能。
<a href="javascript:void(0)" onclick='myfunction <?php echo newsid ?>'Comment</a>
Get the newsid
form the link.从链接中获取newsid
。
<script>
function myfunction(newsid){
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
data:{newsid:newsid},
success: function(comments){
//console.log(komentarji);
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
}
</script>
Get the newid from commenntsUrl page.从commenntsUrl 页面获取newid。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.