【问题标题】:Why onreadystatechange fails when trying to POST data to php script?尝试将数据发布到 php 脚本时,为什么 onreadystatechange 失败?
【发布时间】:2023-03-08 06:34:02
【问题描述】:

当单击提交按钮时,我有以下 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>

【问题讨论】:

    标签: javascript php jquery ajax xmlhttprequest


    【解决方案1】:

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

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

    【讨论】:

    • 现在它将注释添加到数据库中,但我必须刷新才能显示它们。如何解决这个问题?
    • 页面没有神奇更新,需要更新。返回新代码并设置innerHTML/追加新项目。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多