首页 > 解决方案 > 如何使用 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 + "");
}

我会很感激你的帮助。

编辑:解决了!函数名称不能包含连字符。它现在正在工作

标签: javascriptphpajax

解决方案


推荐阅读