簡體   English   中英

如何將PHP中的數組返回到$ .ajax成功函數

[英]How to return array in php to $.ajax success function

我想將json數組返回給調用$.ajax function ,但是我只得到了預期數組的最后一項。 也許我不產生數組?

如果我單擊ID為“ btn_getAnswers”的按鈕,則會觸發“ "$("#btn_getAnswers").click" ,並執行代碼"DBCOMANSWERS" 我希望"$result" DBCOMANSWERS”中的"$result"是一個填充有我的MYSQL數據庫值的數組。 我返回格式為JSON的"$result" 返回的結果應附加到id為“ output”的段落中。 到目前為止,一切正常,但是我除了要返回的三個字符串並附加到該段落之外,現在僅附加了一個,即數據庫中最后一個捕獲的條目。

我真的看不到我必須在哪里添加附加循環或其他內容。 返回的$ result可能不只是數組的最后一個條目,因為它會被覆蓋嗎?

Index.html:

<!DOCTYPE html>
<html>
    <head>
        <script src="jquery-1.12.3.js"></script> <!-- Import the jquery extension -->
        <script>
            $(document).ready(function () {
                $("#btn_getQuestion").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "DBCOMQUESTIONS.php?q=" + $("#input").val(),
                        success: function (result) { //Performs an async AJAX request
                            if (result) {
                                $("#output").html(result); //assign the value of the result to the paragraph with the id "output"
                            }
                        }
                    });
                });

                $("#btn_getAnswers").click(function () {
                    $.ajax({
                        type: "POST",
                        url: "DBCOMANSWERS.php?q=" + $("#input").val(),
                        success: function (result) { //Performs an async AJAX request
                            if (result) {
                                $("#output").append(result);
                            }
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <p id="output">This is a paragraph.</p>

        <input id="input"/>
        <button id="btn_getQuestion">Question</button>
        <button id="btn_getAnswers">Answers</button>

    </body>
</html>

DBCOMANSWERS.php:

<!DOCTYPE HTML>
<head>
</head>
<body>
    <?php
        include("connection.php");  //includes mysqli_connent with database
        include("ErrorHandler.php"); //includes error handling function
        set_error_handler("ErrorHandler"); //set the new error handler

        $q = intval($_GET['q']);

        $sql="SELECT * FROM tbl_answers WHERE QID ='".$q."'"; //define sql statement

        $query = mysqli_query($con,$sql); // get the data from the db

        while ($row = $query->fetch_array(MYSQLI_ASSOC)) { // fetches a result row as an associative array
            $result = $row['answer'];
        }

        echo json_encode($result); // return value of $result
        mysqli_close($con); // close connection with database
    ?>
</body>
<html> 

嘗試:刪除所有html標簽,然后

include("ErrorHandler.php"); //includes error handling function
 set_error_handler("ErrorHandler"); //set the new error handler

從ajaxed php文件中,創建結果數組並將每個結果附加到該數組

    $result = []
     while ($row = $query->fetch_array(MYSQLI_ASSOC)) { // fetches a result row as an associative array
                $result[] = $row['answer'];
            }
header('Content-Type: application/json');//change header to json format

在您的ajax函數中,您需要執行一個循環:

success: function(result){ //Performs an async AJAX request
               result.forEach(function(i,v){
                   $("#output").append(v.answer);
                 })

            }}

你需要做兩件事

刪除html並添加數組集合。 這就是您的DBCOMANSWERS.php必須看起來像的樣子

<?php
    include("connection.php");  //includes mysqli_connent with database
    include("ErrorHandler.php"); //includes error handling function
    set_error_handler("ErrorHandler"); //set the new error handler

    $q = intval($_GET['q']);

    $sql="SELECT * FROM tbl_answers WHERE QID ='".$q."'"; //define sql statement

    $query = mysqli_query($con,$sql); // get the data from the db
    $result = [];
    while ($row = $query->fetch_array(MYSQLI_ASSOC)) { // fetches a result row as an associative array
        $result [] = $row['answer'];
    }
    mysqli_close($con); // close connection with database
    header('Content-Type: application/json');
    echo json_encode($result); // return value of $result

?>

然后在您的html中,如@madalinivascu建議

success: function(result){ //Performs an async AJAX request
           result.forEach(function(i,v){
               $("#output").append(v.answer);
             })

        }}

嘗試:

$result = []
 while ($row = $query->fetch_assoc()) { // fetches a result row as an associative array
            $result[] = $row['answer'];
}

參考:

http://php.net/manual/en/mysqli-result.fetch-array.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM