我正在尝试实施一个小型聊天应用程序,用户可以与任何一个在线用户进行文本聊天。 我背后的逻辑是如下:
Login first.
Fetch the users who are online from DB and show them as list of online users.
Click on the users, then another small window is opening for text chatting.
Create a form(two hidden fields- one is for sender id and another is for receiver id, one textarea and a button for submitting) for this chatting.
Through jQuery, fill the value of receiver id.
By session id, fill the value of sender id.
After submitting the button, I call a page through ajax jquery which is responsible to insert and show the current data from DB.
我的ajaxJquery代码如下:
$(document).ready(function(){
$('#send_btn').click(function(){
var receiver_id = $('#hide_receiver_id').val();
var sender_id = $('#hide_sender_id').val();
var messagebox = $('#messagebox').val();
$.ajax({
type:"POST",
url:"chat_history.php?receiver_id="+receiver_id+"&sender_id="+sender_id+"&message="+messagebox,
success:function(result){
$('#history').html(result);
}
});
$('#messagebox').val('');
});
});
</script>
到此为止,它的工作正常。但我需要自动加载<div id="history"></div>
部分。为此,我也想在jQuery中使用setInterval()
。我的代码就像:
<script type="text/javascript">
var auto_refresh = setInterval(
function (){
$('#history').load("chat_history.php?receiver_id=''&sender_id=<?php echo $_SESSION['id']?>&message=").fadeIn("fast");
}, 1000); // refresh every 1000 milliseconds
</script>
但在这种情况下,如何在receiever_id
中传递load()
的值,这是查找数据库中各自数据所必需的?
请告诉我您是否清除了该要求。
提前致谢。
答案 0 :(得分:0)
<script>
$(function () {
// function wide variables
var receiver_id = $('#hide_receiver_id').val();
var sender_id = $('#hide_sender_id').val();
var messagebox = $('#messagebox').val();
// button click
$('#send_btn').click(function () {
receiver_id = $('#hide_receiver_id').val();
sender_id = $('#hide_sender_id').val();
messagebox = $('#messagebox').val();
$.ajax({
type : "POST",
url : "chat_history.php?receiver_id=" + receiver_id + "&sender_id=" + sender_id + "&message=" + messagebox,
success : function (result) {
$('#history').html(result);
}
});
$('#messagebox').val('');
});
var auto_refresh = setInterval(function(){
$('#history').load("chat_history.php?receiver_id="+receiver_id+"&sender_id=<?php echo $_SESSION['id']?>&message=").fadeIn("fast");
}, 1000); // refresh every 1000 milliseconds
});
</script>