如何用AJAX告诉PHP在文章下面显示哪些注释

How to tell PHP which comments to show under the article with AJAX?

本文关键字:显示 注释 文章 AJAX 何用 告诉 PHP      更新时间:2023-09-26

我正在为我的网站建立一个新闻页面,但我卡住了用ajax显示正确的评论…

commentsLoad.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;
?>

我不知道如何传递正确的'NEWSID'

网站图片:http://prntscr.com/8nwy8k

我如何将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);
 }              
});

所以现在如果我改变data:{newsid:'1 or 2 or 3…'}我得到了我想要的注释,但是我不知道如何把那个ID变成一个变量。

可以使用onClick事件。

解释:

Comment链接如下所示

<a href="javascript:void(0)" onClick="getComments('<?php echo $YOUR_ARTICLE_ ID?>')">Comments</a>

然后你可以在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);
        }              
    });
}

尝试在评论链接中设置onclick功能。

<a href="javascript:void(0)" onclick='myfunction <?php echo newsid ?>'Comment</a>

从链接中获取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>

从commentsurl页面获取新标题