【发布时间】:2019-11-20 04:33:15
【问题描述】:
所以我正在尝试使用 AJAX 创建一个公共聊天应用程序。我希望它工作的方式是:用户在文本区域中键入内容并单击“发送”按钮,AJAX 会将此消息发布到 php 文件中,然后将该消息保存在数据库中。在同一页面上还有一个带来消息的 GET 请求,由另一个 PHP 脚本组织并将它们写入“屏幕”div。我已经为此工作了一周,我发现的所有 ajax 教程都有两个问题:
1:他们使用 jQuery,我正在学习 Javascript,还不想学习 jQuery,所以我的代码是纯 JS,我也不想仅仅因为它的 AJAX 类而导入整个库 2:他们只解释了如何对静态 URL 或 txt 文件进行简单的 GET/POST 请求,而我需要刷新内容而无需重新加载,因为它是一个聊天室。
因此,经过几天又几天的头撞墙,我得出的结论是,在这里问我的问题是唯一的解决方案。我已经添加了尽可能多的 cmets,我还在这里分别包含了 PHP、JS、HTML 代码。我正好有 3 个问题:
1:我怎样才能每 5 秒刷新一次 div,我知道如何使用 jQuery 来做到这一点,但我还是需要 vanilla JS。 我尝试像这样将第 24 行更改为第 29 行:http.onload = setInterval(function(){...},5000);但是尽管 div 确实刷新了,但我看到的唯一消息是“未定义”,我不知道是什么原因造成的。 2:我发送消息的 POST 请求在 Javascript 点击事件监听器中的函数内不起作用,我点击发送按钮,在开发工具的网络选项卡中没有任何反应我看到 get.php 响应通常属于到 GET 请求但没有 POST 请求。 3:我的聊天室的架构还可以吗,还是你建议一个更好、更高效的? 谢谢你! 这是我的 HTML:
<!DOCTYPE HTML>
<html lang = "en">
<head>
<title>Chat</title>
<meta charset = "UTF-8" />
</head>
<body>
<a href="logout.php">log out</a>
<!-- this is the div i want the messages from the other users to be displayed in-->
<div id="screen">
</div>
<!-- this is the text area where the user will type their message -->
<form method="POST">
<textarea name="room" id="room" cols="100" rows="10">
</textarea>
<!-- this is the send button-->
<input type="submit" value="send" name="send" id="send">
</form>
这是我的 JS:
<script>
// show old messages from the user & other users
var old = new XMLHttpRequest();
old.open("GET" , "get.php" , true);
old.onload = function display()
{
var screen = document.getElementById('screen');
// im using inner html so i can edit the message's font/color etc in php
screen.innerHTML = this.responseText;
}
old.send();
// bind the value of the text area to a variable
var data = document.getElementById("room").value;
var send = document.getElementById('send');
// i want the message to be sent only fter the button is pressed
send.addEventListener("click" , send);
function send() {
var http = new XMLHttpRequest();
http.open("POST" , "chat.php" , true);
// perhaps the problem is that i am choosing a wrong header here?
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onload = function()
{
if(http.readyState == 4 && http.status == 200)
{
console.log('ok');
}
}
http.send({message: data});
}
</script>
如果你们需要我的 PHP,我也可以发送我的两个 PHP 文件(get.php 和 chat.php)。
【问题讨论】:
-
作为一个经验丰富的 webdev,我强烈建议你引入 jQuery,即使只是为了那些 AJAX 调用,它真的不需要学习,而且会让你头疼。通过不将它用于一些简单的事情,您将专注于 Web 开发的细节,当您尝试建立一个快速聊天室并学习一些现在对您没有真正帮助时其他概念。
-
谢谢你,我正在构建这些项目来学习,因为这是我的爱好,所以我不介意构建它们是否需要时间,如果我曾经为一家公司工作,我肯定会使用最快的方法但现在我正在学习 javascript
标签: javascript php html ajax