繁体   English   中英

无法使用Ajax将javascript变量发送到php文件

[英]Unable to send javascript variable to php file using ajax

我想将javascript变量发送到php文件,该变量在网页上显示注释。

我能够将此js变量发送到其他一些php文件,但无法通过此comment-list.php文件执行此操作。 我想JSON有问题。

function listComment() {

        $.ajax({
            url: "Komentarji/comment-list.php",
            data : {page_num: page_num},
            type : 'post',
            success : function(response) {
            }
        });

        $.post("Komentarji/comment-list.php", function(data) {
                            var data = JSON.parse(data);
.
.
.

该函数在这里调用:

$(document).ready(function() {
        listComment();
    });

在comment-list.php内部,我尝试获取随ajax发送的变量。 但是,它不起作用,评论也不会显示在页面上。 如果删除此行,则注释会再次起作用(但是,当然,我不会获得发送的变量)。

$num = $_POST['page_num'];

$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";

$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
    array_push($record_set, $row);
}
mysqli_free_result($result);

mysqli_close($conn);
echo json_encode($record_set);

这是javascript变量和随附的php文件。

<script>
var page_num = 1;
</script>
<?php
include($_SERVER["DOCUMENT_ROOT"]."/index.php");
?>

我在控制台中收到此错误:Uncaught SyntaxError:意外的令牌<在JSON.parse()位置0的JSON中

正如伯爵所说,如果我删除用post获得变量的行,此错误将消失。

您不应该使用$.ajax$.post来做同样的事情,选择一个,我会说删除$.post一个,并且不要忘记设置exit; 在回显响应后的语句,以避免PHP处理其他代码(如果有的话),也值得一提,但不是必需的,您可以将dataType放入json,以便在$.ajax调用中将dataType: 'json'用作dataTypedataType用于告诉jQuery什么期望将其作为服务器的响应类型,因为您通过使用JSON进行编码来回显响应,因此,如果事先使用dataType ,则无需在JS端解析响应。

 $.ajax({
        url: "Komentarji/comment-list.php",
        data : {page_num: page_num},
        type : 'post',
        dataType: 'json',
        success : function(response) {
            console.log(response); //will show the result of echo json_encode($record_set); from your PHP
        }
    });


$num = $_POST['page_num'];

$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";

$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
    array_push($record_set, $row);
}
mysqli_free_result($result);

mysqli_close($conn);
echo json_encode($record_set);
exit; //exit statement here

在与希望使用$.post方法的OP进行讨论之后,这就是完成的方法,将数据作为对象传递给第二个属性(更多信息在此处 ):

$.post("Komentarji/comment-list.php", {page_num: page_num});

只需在JS脚本中将格式JSON转换为

$.ajax({
    url : 'Komentarji/comment-list.php',
    type: "POST",
    data: page_num:page_num,
    dataType: "JSON",
    success: function(data)
    {
        console.log(data);            
    },
    error: function (jqXHR, textStatus, errorThrown){
        console.log(errorThrown);
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM