我有一个问题,使我的聊天刷新不断。
我是这样做的:
我将所有消息保存在与PHP连接的MySQL数据库中,用PHP加载消息并使用PHP发布消息,我有jQuery使消息在点击提交时发送到聊天框。
我的网站与聊天
JSFIDDLE
我的问题是,当我和一个朋友聊天,我们必须刷新网站每次有人写东西。我想让聊天框不断刷新。我试过$('#example').load(document.URL + ' #example');
,但它不起作用,有人能帮帮我吗?
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>ChatBox</title>
<script src="http://code.jquery.com/jquery-1.11.3.min.js" charset="utf-8"></script>
<script>
$(document).ready(function(){
$("#content").load("ajaxload.php");
$("a.btn").click(function(){
$.post('ajaxPost.php', $('#userarea').serialize(), function(data){
$('#content').append('<p>'+data+'</p>');
});
return false;
});
});
</script>
<script src="chatbox.js" charset="utf-8"></script>
<link href='http://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="chatbox.css" title="ChatBox" type="text/css" media="screen" charset="utf-8">
</head>
<body>
<h1 id="swegre">
SWEGRE<span>©</span>
</h1>
<div id="wrapper">
<h1>Leave a comment!</h1>
<div id ="content">
<p style="background-color: #b7b7b7">Admin: Here's our chatbox</p>
</div>
<div id="message">
<form id="userarea">
<textarea id="textareamsg" name="messages" rows="2" cols="30" required=""></textarea>
<a href="#" class="btn">POST</a>
</form>
</div>
</div>
</body>
</html>
[CSS不重要](jQuery)
$(document).ready(function(){
$( "a.btn" ).click(function() {
var textValue = $('textarea#textareamsg').val();
if(textValue == "" || textValue == " " || textValue == " " || textValue == " "){
alert('You have to write something in the textarea to post a message');
return false;
}else{
$('#content').append("<p>You: " + textValue + "</p>");
$('textarea#textareamsg').val('');
}
});
});
[AjaxLoad.php] <?php
//conection:
$link = mysqli_connect("localhost","root","123","chat") or die("Error " . mysqli_error($link));
//consultation:
$query = "SELECT * FROM messages" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = mysqli_query($link, $query);
//display information:
while($row = mysqli_fetch_array($result)) {
echo '<p class="other">';
echo $row ["message"] . '</p>';
}
?>
[AjaxPost] <?php
$link = mysqli_connect("localhost","root","123","chat") or die("Error " . mysqli_error($link));
//consultation:
$query = "SELECT * FROM messages" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = mysqli_query($link, $query);
//Code goes here
$message = $_POST['messages'];
mysqli_query($link,"INSERT INTO messages (message)
VALUES ('$message')");
?>
使用ajax重新加载聊天栏
步骤1. Make a chat div
2. Make a ajax call every 10 sec
3. Design a new page called chat.php
4. Update the chat data as per the db.
寓意:每10秒调用一次ajax
你可以使用微软的技术:http://signalr.net/。这个想法是在幕后使用WebSockets。如果不能使用WebSockets,它将转而使用"连续"响应。