如何在php中将数组返回到$ .ajax成功函数

时间:2016-04-08 07:54:13

标签: javascript php jquery mysql ajax

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

如果我点击ID为“btn_getAnswers”的按钮,"$("#btn_getAnswers").click"将被触发,"DBCOMANSWERS"的代码将被执行。我希望“DBCOMANSWERS”中的"$result"是一个填充了我的MYSQL-Database值的数组。我返回格式为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> 

3 个答案:

答案 0 :(得分:3)

尝试: 删除所有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);
                 })

            }}

答案 1 :(得分:3)

你需要做两件事

删除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);
             })

        }}

答案 2 :(得分:1)

TRY:

<ul>
    <li>Selection one</li>
    <li>Selection three</li>
</ul>

参考:

<option>