PHP & Ajax Chat 有时会多次发送消息


PHP & Ajax Chat sending message multiple times sometimes

我的聊天是用php J Query和Ajax进行的。有时当我按发送时,消息会发送多次。

以下是用于发送消息的所有代码。

顶部.php

function chat_send(){
    var text = document.getElementById("chat_text").value;
    document.getElementById("chat_text").value = '';
    document.getElementById("sending").value = 'Sending Message';
    $.post('chat_submit.php', {stage:"send", text:text}, function(data){
        chat_load();        
    });
}
</script>
<div id='chatbox'>
<td><input type='text' name='sending' id='sending' style='background-color:transparent; width:100%' readonly></td>
    <div id='primary'>
        <div id='window'>
        </div>
            <div id='form'>
                <table stlye='width:100%'>
                <tr>
                    <td width='90%'><input type='text' name='chat_text' id='chat_text' style='width:100%;' onKeyDown="if(event.keyCode==13) chat_send();"/></td>
                    <td align='center'><input type='button' id='chat_send' value='Send' onClick='chat_send();' /></td>
                </tr>
                <tr>
                <td><a href="emc.html" target="_blank">Smilies</a></td>
                </tr>
                </table>
            </div>
    </div>
</div>

chat_submit.php

date_default_timezone_set('Europe/London');
session_start();
$username = $_SESSION['username'];
$userid = $_SESSION['id'];
$user = $_SESSION['user'];
require('connect.php');
$stage = $_POST['stage'];
if($stage == "send"){
    $text  = $_POST['text'];
    $time = date("l, H:i:s");
    if($text){
                mysql_query("INSERT INTO chat_chats VALUES('$user', '$time', '$text')");
                $query = mysql_query("SELECT * FROM chat_chats WHERE `user`='$user' AND `time`='$time' AND `text`='text'");
                $numrows = mysql_num_rows($query);
                if($numrows !=0){
                echo "good";
                }
                else
                    echo "error";
    }
    else
        echo "You must enter a message!";

这似乎只是随机开始的,我不确定为什么它会随机多次发送消息。

您可以使用变量来保存 ajax 状态。类似的东西

var sent = false;
function chat_send(){
    ...
}

然后

onClick='if(!sent){chat_send();}else{sent=true;}'

快速而肮脏,但应该可以工作