Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将php中的数组返回到$.ajax success函数_Javascript_Php_Jquery_Mysql_Ajax - Fatal编程技术网

Javascript 如何将php中的数组返回到$.ajax success函数

Javascript 如何将php中的数组返回到$.ajax success函数,javascript,php,jquery,mysql,ajax,Javascript,Php,Jquery,Mysql,Ajax,我想将json数组返回给调用的$.ajax函数,但我只得到预期数组的最后一项。也许我没有生成数组 如果我单击id为“btn_getAnswers”的按钮,“$(“#btn_getAnswers”)。单击“将被激发,并且将执行“DBCOMANSWERS”的代码。我希望“DBCOMANSWERS”中的“$result”是一个填充了MYSQL数据库值的数组。我返回格式为JSON的“$result”。返回的结果应附加到id为“output”的段落中。到目前为止,这还可以,但是我只需要返回三个字符串并附加

我想将json数组返回给调用的
$.ajax函数
,但我只得到预期数组的最后一项。也许我没有生成数组

如果我单击id为“btn_getAnswers”的按钮,
“$(“#btn_getAnswers”)。单击“
将被激发,并且将执行
“DBCOMANSWERS”
的代码。我希望“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>

$(文档).ready(函数(){
$(“#btn_getQuestion”)。单击(函数(){
$.ajax({
类型:“POST”,
url:“DBCOMQUESTIONS.php?q=“+$(“#输入”).val(),
成功:函数(结果){//执行异步AJAX请求
如果(结果){
$(“#output”).html(result);//将结果的值分配给id为“output”的段落
}
}
});
});
$(“#btn_getAnswers”)。单击(函数(){
$.ajax({
类型:“POST”,
url:“DBCOMANSWERS.php?q=“+$(“#输入”).val(),
成功:函数(结果){//执行异步AJAX请求
如果(结果){
$(“#输出”)。追加(结果);
}
}
});
});
});

这是一个段落

问题: 答案
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标记 及

从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标记 及

从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并添加数组集合。这就是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

?>
尝试:

参考:

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

参考:

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


如果您在php中返回JSON,请不要在JSON之外包含html。是否有其他方法返回值
$row['answers']
只返回字符串。如果在php中返回JSON,请不要只包含JSON之外的html。是否有其他方法返回值
$row['answers']
只返回字符串。仍然没有任何内容,是“return”-语句:
echo json\u encode($result)确定?HTML标记仍然需要删除。@apokryfos你是说返回到ajax调用的HTML标记吗?@flohdieter文件DBCOMANSWERS.php中只保留
之间的内容,并删除其余内容。@apokryfos完成了,现在给出的结果就是带有键/值对的数组。谢谢。但我不知道如何将它们附加到段落中@madalin ivascu我尝试了循环,但得到了以下错误消息:
Uncaught TypeError:无法使用'in'运算符在数组(3){[0]=>string(9)“Christian”[1]=>string(5)”Bj中搜索'length'�rn“[2]=>string(6)“Steven”}
仍然没有任何内容,是“return”语句:
echo json\u encode($result)确定?HTML标记仍然需要删除。@apokryfos你是说返回到ajax调用的HTML标记吗?@flohdieter文件DBCOMANSWERS.php中只保留
之间的内容,并删除其余内容。@apokryfos完成了,现在给出的结果就是带有键/值对的数组。谢谢。但我不知道如何将它们附加到段落中@madalin ivascu我尝试了循环,但得到了以下错误消息:
Uncaught TypeError:无法使用'in'运算符在数组(3){[0]=>string(9)“Christian”[1]=>string(5)”Bj中搜索'length'�rn“[2]=>string(6)“Steven”}
应该是
$result[]
我猜。“删除html并添加数组集合”是什么意思?看起来怎么样?@flohdieter您的DBCOMANSWERS.php的内容应该与此答案中的代码相似。查看如何删除
部分,以及
$result=[]
这意味着它是一个数组;在将结果发送回客户端之前。@Sameer Jain最终返回语句是什么样子的?我猜应该是
$result[]
“删除html并添加数组集合”是什么意思?看起来怎么样?@flohdieter您的DBCOMANSWERS.php的内容应该与此答案中的代码相似。查看如何删除
部分,以及
$result=[]
这意味着它是一个数组;在将结果发送回客户端之前。@Sameer Jain最终返回语句是什么样子的?