我正在构建一个网络聊天应用,但是我无法从数据库中检索消息并将它们附加到div。我只是第一次尝试json,所以我觉得我搞砸了。
这是调用php并追加结果的脚本
$.ajax({
type: 'POST',
url: "get_message.php",
data: {msg_id:msg_id},
dataType: "json",
success: function(result){
//all good.
///append to the chats.
for(var i=0; i < result.length; i++){
$("#chats").append("<p>" + result[i]['message'] + "</p>" +
"<p align=right>Sent by " + result[i]['sender'] + " at " +
result[i]['time'] + "</p>");
}
$("#msg").val("");
$('#chats').animate({scrollTop:$('#chats').prop("scrollHeight")}, 500);
}
})
这是它正在调用的php文件;
<?php
$msg_id = $_POST['msg_id'];
require("config.php");
$table = "messages";
$sql = "SELECT message, time, sender FROM $table WHERE chat_id = '$msg_id''";
$messages = array();
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$messages[] = $row;
}
echo json_encode($messages);
} else {
echo "No chats available";
}
?>