我试图做一个网络聊天室,但是当我发送POST请求到服务器,使用此代码:阿贾克斯POST请求,parseerror
var line_count = 0;
$.ajax({
type: 'POST',
url: '../scripts/engine.php',
data: {'method': 'getMsg', 'line_count': line_count},
dataType: 'json',
error: function(request, error) {
alert('Error: '+error);
},
success: function(data) {
$.each(data.messages, function(i, val) {
$('.messages').append(val);
});
line_count = data.srv_count;
}
});
和:
<?php
$method = $_POST['method'];
switch($method) {
case 'postMsg':
$sender = $_SESSION['username'];
$message = $_POST['message'];
$time = $_POST['time'];
fwrite(fopen('chat.txt', 'a'), '<div class="time">[' . $time . ']</div><div class="nickname">' . $sender . '</div>' . $message . "\n");
break;
case 'getMsg':
$log = array();
if(file_exists('chat.txt')) {
$usr_count = $_POST['line_count'];
$srv_msg = explode("\n", file('chat.txt'));
$srv_count = count($srv_msg);
$log['srv_count'] = $srv_count;
if($usr_count < $srv_count) {
$i = 0;
while(list($key, $val) = each($srv_msg)) {
if ($i > $usr_count) {
$log['messages'][i] = $val;
}
$i = $i+1;
}
}
} else {
$log = false;
}
echo json_encode($log);
break;
}
?>
然后我从ajax错误函数中得到这个错误信息: “Error:parseerror”。我多次查看代码,但是我不知道问题出在哪里。 在此先感谢
谢谢大家的快速解答 我检查从服务器返回的值,我undertood这是一个服务器端的问题。 returnded值:
警告:爆炸()预计参数2为字符串,阵列中X给出:\ WWW \根\脚本\ engine.php线
{“srv_count “:0}
我刚编辑我的代码为:
$usr_count = $_POST['line_count'];
$srv_msg = explode("\n", file_get_contents('chat.txt'));
$srv_count = count($srv_msg);
$log['srv_count'] = $srv_count;
if($usr_count < $srv_count) {
$i = 0;
while(list($key, $val) = each($srv_msg)) {
if ($i > $usr_count) {
$log['messages'][$i] = $val;
}
$i = $i+1;
}
}
现在我t的工作正常。
不确定它很重要,但从php中删除中断。也调试$日志,确保它是在有效的json编码。 – Mihai
我该怎么办? –
Thx我将编辑代码 –