【发布时间】: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