为什么onreadystatechange在尝试将数据POST到php脚本时失败

Why onreadystatechange fails when trying to POST data to php script?

本文关键字:php 脚本 失败 POST 数据 onreadystatechange 为什么      更新时间:2023-09-26

我有以下Javascript代码,当单击提交按钮时,使用Ajax将输入数据从notebook.php中的表单发送到数据库。名为addNote()的函数应该通过将数据发布到add.php来处理Ajax操作。

出于某种原因,这不起作用。onreadystate函数似乎失败,并且从未接收到来自add.php的对变量res的响应文本。我不知道为什么。代码中缺少什么吗?

以下是文件notebook.js、notebook.php、的内容

notebook.js:

function addNote() {
    ...
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) { // compelete & OK
            var res = xhr.responseText;
        }
    }
    var notetext = document.getElementById("notetext").value;
    xhr.open("POST", "add.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("notetext=" + notetext);
} 
function main() {
    $("#submitbtn").click(function() {
        addNote();
    });
}
$(document).ready(main);

notebook.php:

...
<body>
    <h1>Notebook</h1>
    <div class="input">
        <form>
            <input type="text" name="notetext" id="notetext">
            <input type="submit" value="Add" id="submitbtn">
        </form>
    </div>
    <ul>
        <?php
            // add stuff to list
        ?>
    </ul>
</body>
</html>

您不会取消单击提交按钮,因此表单会提交页面。

$("#submitbtn").click(function(evt) {
    evt.preventDefault();  //cancel the form submission by cancelling the click action. 
    addNote();
});