通过javascript将POST请求发送到REST

通过javascript将POST请求发送到REST

本文介绍了通过javascript将POST请求发送到REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我读到某处不应使用 XMLHttpRequest .

First, I read somewhere that we should not use XMLHttpRequest.

第二,我是Java语言的新手.

Second, I am a newbie in Javascript.

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

Third, I created a webpage to submit email and password.

<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;
}

此代码不起作用,只是一次又一次地将我重定向到同一页面.

This code is not working and just redirects me to the same page again and again.

请帮助我了解我在做什么错

Please help me understand what am I doing wrong.

推荐答案

您的代码存在的问题是,您不是在拦截"代码.表单的Submit事件,因此它将执行默认行为,即默认行为 POST (因为它没有告诉它去哪里的指令).除非您有机会停止这种默认行为,否则表单将执行此操作.

The problem with your code is that you are not "intercepting" the submit event of your form so it will execute the default behavior which is POST to itself (since it doesn't have an instruction that tells it where to go). Unless you can have a chance to stop this default behavior, the form will perform this action.

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

To intercept the form's submit event you have to tell the browser to watch out of this event and execute a custom function instead of using an event listener like below:

<script>

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

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

</script>

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

This will prevent your form from posting and it will execute your function instead.

这篇关于通过javascript将POST请求发送到REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 13:43