如何将php中的return数组转为$.ajax成功函数

How to return array in php to $.ajax success function

我想 return 一个 json 数组返回调用 $.ajax function,但我只得到预期数组的最后一项。也许我不生产阵列?

如果我点击 ID 为 "btn_getAnswers" 的按钮,"$("#btn_getAnswers").click" 将被触发,"DBCOMANSWERS" 的代码将被执行。我希望 "DBCOMANSWERS" 中的 "$result" 成为一个数组,其中填充了我的 MYSQL- 数据库的值。我把return"$result"格式化为JSON。 returned 结果应附加到 ID 为 "output" 的段落。到目前为止,一切正常,但我除了要 returned 并附加到段落的三个字符串外,现在只附加了一个字符串,即数据库中最后捕获的条目。

我真的看不出我必须在哪里放置循环以进行附加或其他操作。 returned $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

?>

然后按照@madalinivascu 的建议html

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