我想返回一個json數組回到調用$.ajax function
,但我只得到期望數組的最後一項。也許我不生產數組?
如果我點擊ID爲「btn_getAnswers」的按鈕,被觸發,"DBCOMANSWERS"
的代碼將被執行。我想在「DBCOMANSWERS」中的"$result"
是一個填充了我的MYSQL數據庫值的數組。我返回格式爲JSON的"$result"
。返回的結果應附加到ID爲「output」的段落。到目前爲止,這工作正常,但我除了三個字符串被返回並附加到段落,現在只是一個,從數據庫中最後一個捕獲的條目,被追加。
我真的不知道我必須在哪裏放置一個循環來追加或其他。返回的$結果可能不是數組,因爲它被覆蓋了嗎?
的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>
如果您在PHP中返回JSON,請不要包含html o只有JSON。 – jcubic
是否有另一種方法來返回值? '$ row ['answers']'只返回字符串。 – flohdieter