javascript - 如何使用 Ajax(没有 JQuery)在数据库中插入数据?
问题描述
我正在为我的网站创建一个基于 php、mysql 和 ajax 的喊话框。现在我希望用户能够编写消息,使用 Ajax 打开保存文件并使用 php 将消息插入数据库。一切正常 - 除了 ajax 部分。不知何故,它没有打开保存文件。
html:
<input type='text' id='shoutbox-comment' name='shoutbox-msg' style='width: 179px;' value='My message'>
<input type='submit' name='shoutbox-submit' value='ok' onclick='shoutbox-send();'>
我正在为任何数据库请求使用框架 Medoo。我已经使用普通的 html 表单尝试了代码,并且文件本身工作正常。
php “shoutbox-write.php”:
if (!empty($_POST['msg'])){
$userid = $_SESSION['id'];
$message = substr($_POST['msg'],0,200);
$message = xss($message);
$now = time();
$database->insert("shoutbox", ["userid" => $userid, "message" => $message, "time" => $now]);
}
现在是问题部分。我尝试了各种方法,甚至将整个脚本更改为 GET 以查看它是否有效。没有任何效果。第一个 javascript 代码是我从这里获取的。第二个是我之前用过的那个。两者都不起作用。请注意,我想在不使用 JQuery 的情况下解决这个问题。
function shoutbox-send() {
var xmlHttp = new XMLHttpRequest();
var url="<?php echo PATH; ?>divers/shoutbox-write.php";
var message = document.getElementById('shoutbox-comment').value;
var parameters = "msg="+message;
xmlHttp.open("POST", url, true);
//Black magic paragraph
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById('shoutbox-comment').value="";
}
}
xmlHttp.send(parameters);
}
function shoutbox-send() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var message = document.getElementById('shoutbox-comment').value;
document.getElementById('shoutbox-comment').value = "";
}
};
xhttp.open("POST", "<?php echo PATH; ?>divers/shoutbox-write.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("msg=" + message + "");
}
我会很感激你的帮助。
编辑:解决了!函数名称不能包含连字符。它现在正在工作
解决方案
推荐阅读
- vb.net - 性能计数器。如果相同的进程正在运行,我如何访问正确的进程?
- html - 如何将 bootstrap4 导航栏转换为移动侧边栏?
- testing - 只看教学大纲就能通过 ISTQB 考试吗?
- android - React Native Build for android 在 Windows 机器上失败
- java - 如何制作可执行文件
- c# - 如何在 C# 中的控制台中显示数据库值
- javascript - 成功处理表单时显示按钮
- angular - 如何解决 npm 启动问题?
- javascript - 如何在 JS App 中创建 onReady 承诺
- javascript - 为什么移动对象后出现未处理的拒绝(TypeError)错误:无法读取 Redux 应用程序中未定义的属性“过滤器”?