javascript - 通过 javascript 向 REST API 发送 POST 请求

标签 javascript ajax rest

首先,我在某处读到我们不应该使用 XMLHttpRequest

其次,我是 Javascript 的新手。

第三,我创建了一个网页来提交电子邮件和密码。

<form method="POST" onsubmit="return check();">{% csrf_token %}
    <p><b>Login</b></p>
    <input type="email" name="email" placeholder="Email" required></input>
    <input type="password" name="password" placeholder="Password" id='new_password' ></input>
    <span id='message'>{{msg}}</span>
    <button type="submit" onclick="check()" name="Submit"><b>Submit</b></button>
</form>

我的校验函数是

function check() {        
    document.getElementById('message').innerHTML = "checking";
    const url = "https://<hostname/login";
    const data = {
        'email' : document.getElementById('email').value,
        'password' : document.getElementById('password').value
    };

    const other_params = {
        headers : { "content-type" : "application/json; charset=UTF-8" },
        body : data,
        method : "POST",
        mode : "cors"
    };

    fetch(url, other_params)
        .then(function(response) {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error("Could not reach the API: " + response.statusText);
            }
        }).then(function(data) {
            document.getElementById("message").innerHTML = data.encoded;
        }).catch(function(error) {
            document.getElementById("message").innerHTML = error.message;
        });
    return true;
}

此代码无效,只是一次又一次地将我重定向到同一页面。

请帮助我理解我做错了什么。

最佳答案

您的代码的问题在于您没有“拦截”表单的提交事件,因此它将执行默认行为,即 POST 到自身(因为它没有指令告诉它去哪里)。除非您有机会停止此默认行为,否则表单将执行此操作。

要拦截表单的提交事件,您必须告诉浏览器留意此事件并执行自定义函数,而不是使用如下所示的事件监听器:

<script>

document.getElementById('whatever-form-id')
  .addEventListener('submit', check);

function check(e) {
  e.preventDefault();
  // and now anything else you want to do.
}

</script>

这将阻止您的表单发布,而是执行您的功能。

关于javascript - 通过 javascript 向 REST API 发送 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52983484/

相关文章:

search - 如何使用可选参数设计用于搜索的 RESTful URL?

javascript - 首次登录时的 React-Native 欢迎屏幕

php - 根据下拉选择的结果填充文本字段 - 均使用 php mysql ajax 请求

javascript - 从数据库中获取数据并在 AngularJS 的 ng-repeat 中使用它

jQuery AJAX 成功背景

javascript - 无法访问 $.ajax.done() 中的全局变量

database - 有 2 个应用程序查询 1 个数据库是否整洁

wcf - 对 Http 动词感到困惑

php - CKEditor - CKFinder 在我上传图片后不会自动创建缩略图

javascript - 通过单击按钮本身关闭下拉菜单