我是AJAX和PHP的新手,但是我不太理解这段代码:
https://github.com/Artifx/PHP-and-MySQL-Web-Development-5th-Edition/blob/master/Chapter23/client.js
var pollServer = function() {
$.get('chat.php', function(result) {
if(!result.success) {
console.log("Error polling server for new messages!");
return;
}
$.each(result.messages, function(idx) {
var chatBubble;
if(this.sent_by == 'self') {
chatBubble = $('<div class="row bubble-sent pull-right">' +
this.message +
'</div><div class="clearfix"></div>');
} else {
chatBubble = $('<div class="row bubble-recv">' +
this.message +
'</div><div class="clearfix"></div>');
}
$('#chatPanel').append(chatBubble);
});
setTimeout(pollServer, 5000);
});
}
$(document).on('ready', function() {
pollServer();
$('button').click(function() {
$(this).toggleClass('active');
});
});
$('#sendMessageBtn').on('click', function(event) {
event.preventDefault();
var message = $('#chatMessage').val();
$.post('chat.php', {
'message' : message
}, function(result) {
$('#sendMessageBtn').toggleClass('active');
if(!result.success) {
alert("There was an error sending your message");
} else {
console.log("Message sent!");
$('#chatMessage').val('');
}
});
});
是否仅在发出POST请求后才触发GET请求?该逻辑有什么问题,使得必须每5秒运行一次pollServer
函数?