javascript - 为什么我必须在这个聊天应用程序中不断触发 GET 请求?
问题描述
我是 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 请求吗?这个逻辑有什么问题,需要pollServer
每 5 秒运行一次函数?
解决方案
推荐阅读
- javascript - 自定义“PrivateRoute”组件返回一个 React-Router 路由 || 重定向导致不变违规
- c# - Manifestresource 流加载对某些文件给出空引用期望
- javascript - 为什么包含空格和数字的字符串可以解析为日期?
- javascript - 如何将图像适合 div?
- twitter-bootstrap - 将选择字段插入符号向左浮动(引导程序 4)
- ios - 语言方案已从旧设备中删除
- python - 从表达式 sympy 中获取变量
- node.js - npm ENOENT 没有这样的文件或目录,打开 {path}/package.json
- c - 如何在二进制搜索中使用结构?
- swift - 将 UnsafeMutablePointer 的实部提取为浮点数并将其存储在数组中