javascript - 使用ajax提交表单时出现错误

标签 javascript node.js ajax

当我提交post方法表单时,给定输入字段值,但提交时没有获取。如果我在 Jquery 中使用 Ajax 调用,表单值会序列化并正确提交,但在 javascript 中,使用 FormData 进行 Ajax 调用时会出现错误。

谁能解决我的问题。

错误:

  1. Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)

  2. apollo.model.save.unsetkey: Primary Key Field: name must have a value

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form id="myForm" method="post" action="">
    <div>
        <label for="name">Enter name:</label>
        <input type="text" id="name" name="name">
    </div>
    <div>
        <label for="surname">SurName:</label>
        <input type="text" id="surname" name="surname">
    </div>
    <div>
        <label for="age">Age:</label>
        <input type="text" id="age" name="age">
    </div>
    <input type="submit" value="Submit!"  onclick="loadForm()">
</form>
<p id="demo"></p>

<script>
    function loadForm() {
        var xhttp = new XMLHttpRequest();
        var myForm = document.getElementById('myForm');
        var formData = new FormData(myForm);

        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("demo").innerHTML =
                        this.responseText;
            }
        };
        xhttp.open("POST", "http://127.0.0.1:8080/user", true);
        xhttp.setRequestHeader('Accept', 'application/json');
        xhttp.setRequestHeader('Content-Type', 'application/json');
        var data = JSON.stringify(formData);
        console.log('data = ', data);
        xhttp.send(data);
    }
</script>
</body>
</html>

最佳答案

您不会停止表单的默认提交,因此当有人单击提交按钮时,表单将通过使用 Ajax 正常提交。解决方案是将监听器绑定(bind)到表单提交并防止默认行为。

试试这个:

document.querySelector("#myForm").addEventListener("submit", function (event) {
    event.preventDefault();
    // ... Ajax call here ...
})

关于javascript - 使用ajax提交表单时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43875566/

相关文章:

node.js - 如何使用 ReactJS 和 SendGrid 发送电子邮件?

php - 如何通过 JSON 从 AJAX 请求中获取 PHP 数组(多个——循环)?

jquery - 如何在 jQuery 中的 POST 请求中转义 & ?

javascript - Spotify - 从 URI 空数据获取轨道

node.js - 如何在 MongoDB collection.find() 上获得回调

javascript - 我收到重复 key 错误 -- MongoError : E11000 duplicate key error collection. 我确实有 2 个集合、用户和个人资料。

jQuery .ajax post 因大型 JSON 对象而失败

javascript - 从多维数组中提取值

javascript - getElementById 返回 NaN

javascript - 为什么我的 map 函数另外添加 2 个空的 'li' ?