我有一个更新聊天室的 JavaScript 更新脚本,如下所示:
// Update chat rooms //
if(time > lastchatupdatetime + .4){
for(var i in this.chatroomlist){
var chattext = AJAX('server/updateChatRoom.php','id='+i);
document.getElementById("S3DChatRoom_" + i).innerHTML = chattext;
}
lastchatupdatetime = time;
}
AJAX 函数如下所示:
var AJAX = function (page, send, callback){
if(typeof callback == 'undefined') callback = function() {};
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function (){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
chatresponse = xmlhttp.responseText;
callback();
}
}
xmlhttp.open("POST",page,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(send);
return chatresponse;
}
PHP 脚本如下所示:
$chatroomid = isset($_POST['id'])?$_POST['id']:0;
$chatroomdir = "../chatrooms/";
$chatroomurl = $chatroomdir . 'chatroom_' . $chatroomid . ".json";
if(file_exists($chatroomurl)){
$chattext = json_decode(file_get_contents($chatroomurl),TRUE);
if($chattext == TRUE){
foreach($chattext as $i){
echo $i[0] . ": " . $i[1] . "<br>";
}
}
} else {
echo "Chatroom listed does not exist";
}
在我提交新的聊天文本后,文本会被写入并在第一次更新时显示,然后在下一次更新时会从.json
保存聊天内容的文件中删除。这对我来说完全没有意义,而且我编写了类似的聊天应用程序,即使远程存在也没有这个问题。这发生在 WebMatrix 的 IIS-Express PHP 和 WAMP 的 PHP 上。
这是聊天提交 PHP 脚本(其中包含一些调试代码——调试代码工作正常,所有信息都正确写入):
$chatroomid = $_POST['id'];
$chatroomtext = $_POST['chattext'];
$clientid = $_POST['clientid'];
$chatroomdir = "../chatrooms/";
$chatroomurl = $chatroomdir . "chatroom_" . $chatroomid . ".json";
$currentchattext = file_get_contents($chatroomurl);
$currentchattext = json_decode($currentchattext, TRUE);
$currentchattext[] = array($clientid,$chatroomtext);
file_put_contents("debug2",json_encode($currentchattext));
$success = file_put_contents($chatroomurl, json_encode($currentchattext));
file_put_contents("debug",json_encode($currentchattext), FILE_APPEND);
if($success == FALSE){
echo 0;
} else {
echo 1;
}
这是用于发布的 JavaScript:
var submitChatTextconfirm;
document.getElementById("S3DTextInput_"+name).addEventListener("keypress",function(event) {
if(event.keyCode == 13){
submitChatTextconfirm = AJAX("server/submitChatText.php", "id=" + name + "&chattext=" + document.getElementById("S3DTextInput_"+name).value + "&clientid=" + this.clientid);
console.log(document.getElementById("S3DTextInput_"+name).value);
console.log(submitChatTextconfirm);
}
},true);
if(submitChatTextconfirm == 1){
console.log("Chat sent");
} else {
console.log("ERROR: Chat text failed to send");
}