gpt4 book ai didi

javascript - PHP/AJAX : Ajax request to php not working, 未将行放入 div

转载 作者:行者123 更新时间:2023-11-30 00:21:33 26 4
gpt4 key购买 nike

我正在进行 php 聊天,但在使用 ajax 检查 mysql 数据库并将数据放入 div 时遇到一些问题。这是我的代码:

HTML

<div id="chatbox">
<div class="chatheader"><div class="chatheadertext">chatheader</div></div>
<div id="chatcontainer">
<div class="chatpadding">
<div id="chatmessages">
<div class="chat-replies">
<div class="chat-reply-container">
<div class="chat-reply-avatar">
<img src="img/default_avatar.png">
</div>
<div class="chat-reply-chat">
<span class="chat-reply-author">testuser</span><br>
<span class="chat-reply-content">test message goes here</span>
</div>
</div>
</div>
</div>
</div>
<form id="form" action="">
<textarea class="chatchat" id="message" placeholder="Type message here!"></textarea>
</form>
</div>
</div>

JavaScript

<script>
$(".chatheader").on("click", function () {
$("#chatcontainer").slideToggle();
});
$("textarea").keyup(function(e){
if((e.keyCode ? e.keyCode : e.which) == 13) {
//The enter button has been pressed
}
});
$(function ()
{
$.ajax({
url: 'ajax.php',
data: "",
dataType: 'json',
success: function(data)
{
$('#chatmessages').html("<div class='chat-replies'>
<div class='chat-reply-container'>
<div class='chat-reply-avatar'>
<img src='img/default_avatar.png'>
</div>
<div class='chat-reply-chat'>
<span class='chat-reply-author'>testuser</span><br>
<span class='chat-reply-content'>test message goes here</span>
</div>
</div>
</div>");
}
});
});
</script>

PHP

<?php
$con = mysqli_connect('localhost','root','','chat');
$query = mysqli_query($con,"SELECT * FROM `messages`");
$msgnum = mysqli_num_rows($query);
$array = mysqli_fetch_row($query);
echo json_encode($array);
?>

所以基本上我想做的是使用ajax联系php文件,然后该文件将检查mysql数据库中的表并将它们编码为json,在索引页面上,聊天框应该由第一个javascript出现功能正常,但不向上滑动。知道是 ajax 正在执行此操作,特别是 $('#chatmessages').html();线。当我从该行删除代码时,聊天框出现,但里面是空的。我做错了什么,我该怎么做,以便当它接触时,对于数据库中找到的每一行,它都会回显

<div class='chat-replies'>
<div class='chat-reply-container'>
<div class='chat-reply-avatar'>
<img src='img/default_avatar.png'>
</div>
<div class='chat-reply-chat'>
<span class='chat-reply-author'>testuser</span><br>
<span class='chat-reply-content'>test message goes here</span>
</div>
</div>
</div>

因此,如果数据库中有大约 50 行,它会为每一行回显该脚本,并且会有一个 overflow-y:scroll关于<div id="chatmessages">所以它不会溢出。预先感谢任何可以提供帮助的人!

最佳答案

如果 AJAX 调用的成功回调中有 json 数据,您可以迭代所有记录并将每条记录附加到聊天 div

 success: function(data)        
{
$.each(data,function(index,dataRecord){
document.getElementById('chatmessages').innerHTML +="html content goes here";
});
//scroll down your div,make sure you should have propery, overflow-y:scroll
document.getElementById('chatmessages').scrollTop=100000;
}

希望这会有所帮助,谢谢

关于javascript - PHP/AJAX : Ajax request to php not working, 未将行放入 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23192809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com