【问题标题】:How to return array in php to $.ajax success function如何将 php 中的数组返回到 $.ajax 成功函数
【发布时间】:2016-04-08 07:54:12
【问题描述】:

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

如果我单击 ID 为“btn_getAnswers”的按钮,"$("#btn_getAnswers").click" 将被触发,"DBCOMANSWERS" 的代码将被执行。我希望“DBCOMANSWERS”中的"$result" 是一个填充了我的MYSQL 数据库值的数组。我以 JSON 格式返回 "$result"。返回的结果应附加到 id 为“输出”的段落。到目前为止,这工作正常,但我除了要返回并附加到段落的三个字符串之外,现在只有一个,即从数据库中捕获的最后一个条目,被附加。

我真的看不出我必须在哪里放置循环以进行追加或其他任何事情。返回的 $result 可能不是一个数组,只是数据库的最后一个条目,因为它被覆盖了吗?

索引.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> 

【问题讨论】:

  • 如果您在 php 中返回 JSON,请不要仅在 JSON 之外包含 html。
  • 还有其他方法可以返回值吗? $row['answers'] 只返回字符串。

标签: javascript php jquery mysql ajax


【解决方案1】:

你需要做两件事

删除 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[]
  • 什么是“删除html并添加数组集合”。意思是?它看起来怎么样?
  • @flohdieter 你的 DBCOMANSWERS.php 的内容应该像这个答案中的代码一样。看看&lt;html&gt;.. 部分是如何被删除的,$result=[] 意味着它是一个数组。
  • 正如@madalinivascu put header('Content-Type: application/json');在将结果发送回客户端之前。
  • @Sameer Jain 最后的return语句是什么样子的?
【解决方案2】:

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

            }}

【讨论】:

  • 还是什么都没有,是“返回”语句:echo json_encode($result); ok?
  • HTML 标记仍需删除。
  • @apokryfos 你的意思是返回给ajax调用的HTML标签吗?
  • @flohdieter 在文件 DBCOMANSWERS.php 中只保留 &lt;?php ... ?&gt; 之间的内容并删除其余部分。
  • @apokryfos 完成了,现在给定的结果只是带有键/值对的数组。谢谢。但我不知道如何将它们附加到段落中。 @madalin ivascu 我尝试了循环但收到以下错误消息:Uncaught TypeError: Cannot use 'in' operator to search for 'length' in array(3) { [0]=&gt; string(9) "Christian" [1]=&gt; string(5) "Bj�rn" [2]=&gt; string(6) "Steven" }
【解决方案3】:

试一试:

$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

【讨论】:

    猜你喜欢
    • 2013-10-30
    • 2015-06-29
    • 2013-03-10
    • 1970-01-01
    • 2019-07-06
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多