簡體   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