通过javascript向RESTAPI发送POST请求

通过javascript向RESTAPI发送POST请求,javascript,ajax,rest,Javascript,Ajax,Rest,首先,我在某个地方读到,我们不应该使用XMLHttpRequest 第二,我是Javascript的新手 第三,我创建了一个网页来提交电子邮件和密码 <form method="POST" onsubmit="return check();">{% csrf_token %} <p><b>Login</b></p> <input type="email" name="email" placeholder="Emai

首先,我在某个地方读到,我们不应该使用
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>
{%csrf\u令牌%}
登录

{{msg}} 提交
我的支票功能是

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;
}
函数检查(){
document.getElementById('message').innerHTML=“checking”;
const url=“https://1)您的验证函数始终返回true
2) 当您使用
fetch..then
时,它的承诺可以在return语句之后执行

因此,您的表单将被一次又一次刷新。您应该返回false,并在收到
onSuccess
响应时使用JavaScript手动提交表单

<script>
    function check(event) {
        document.getElementById('message').innerHTML = "checking";

        const url = "https://localhost:8080/login";
        const data = {
            'email' : document.getElementById('email').value,
            'password' : document.getElementById('new_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) {
                    alert(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 false;
    }
</script>

<form method="POST" onsubmit="return check();">{% csrf_token %}
    <p><b>Login</b></p>
    <input type="email" id = "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" name="Submit"><b>Submit</b></button>
</form>

功能检查(事件){
document.getElementById('message').innerHTML=“checking”;
常量url=”https://localhost:8080/login";
常数数据={
“电子邮件”:document.getElementById('email')。值,
“密码”:document.getElementById('new_password')。值
};
常数其他参数={
标题:{“内容类型”:“应用程序/json;字符集=UTF-8”},
正文:数据,
方法:“张贴”,
模式:“cors”
};
获取(url、其他参数)
.然后(功能(响应){
if(response.ok){
警报(response.json());
}否则{
抛出新错误(“无法到达API:+response.statusText”);
}
}).then(功能(数据){
document.getElementById(“message”).innerHTML=data.encoded;
}).catch(函数(错误){
document.getElementById(“message”).innerHTML=error.message;
});
返回false;
}
{%csrf_令牌%}
登录

{{msg}} 提交
更新:

页面未刷新,显示错误消息:

我检查过,您的代码中有一些错误,请这样使用

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

        const url = "https://hostname/login";
        const data = {"email" : document.getElementById('email').value,
                    'password' : document.getElementById('new_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;
    }
  </script>
{%csrf\u令牌%}
登录

{{msg}} 提交 功能检查(事件){ event.preventDefault(); document.getElementById('message').innerHTML=“checking”; 常量url=”https://hostname/login"; 常量数据={“email”:document.getElementById('email')。值, “密码”:document.getElementById('new_password')。值 }; 常数其他参数={ 标题:{“内容类型”:“应用程序/json;字符集=UTF-8”}, 正文:数据, 方法:“张贴”, 模式:“cors” }; 获取(url、其他参数) .然后(功能(响应){ if(response.ok){ 返回response.json(); }否则{ 抛出新错误(“无法到达API:+response.statusText”); } }).then(功能(数据){ document.getElementById(“message”).innerHTML=data.encoded; }).catch(函数(错误){ document.getElementById(“message”).innerHTML=error.message; }); 返回true; }
然后,通过更改您的帖子URL来进行测试,以更正帖子URL是否有效,若要进行更多测试,请使用浏览器检查器工具查看您的ajax请求

我也为你的现场测试做了准备


谢谢

首先,我想在从REST API获取数据后了解您的对象是什么

第二,html代码中也有错误,当表单元素上已经有了一个
onsubmit
时,不需要在submit按钮上添加
onclick

解决方案, 改变
onsubmit=“检查(事件);”

函数检查(e){e.preventDefault()…}//您可以删除返回true

在这里,我只是想说一下,但是你已经在标题中将
内容类型设置为
application/json
,但是你的主体不是一个json字符串

试着让你的身体与标题相匹配

const other_params = {
  headers : { "content-type" : "application/json; charset=UTF-8"},
  body : JSON.stringify(data),
  method : "POST",
  mode : "cors"
};
编辑

因此,在重新阅读您的问题后,我认为现在发生的是您将
按钮设置为
提交
类型,而现在发生的是当您单击按钮时,您的表单通过良好的旧表单帖子发布,您的页面从回发中刷新

如果您想自己使用fetch处理表单发布,请将按钮类型更改为
按钮
,并且表单不应再实际发布,那么其他所有内容都将由单击事件处理程序处理

另外,当您使用时,还可以从表单标记中删除
方法
onsubmit
属性

所以你的表格应该是这样的

<form>
    <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="button" onclick="check()" name="Submit"><b>Submit</b></button>
</form>

登录

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

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

<script>

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

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

</script>

document.getElementById('whatever-form-id')
.addEventListener(“提交”,检查);
功能检查(e){
e、 预防默认值();
//现在你还想做什么。
}

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

使用
窗口重定向。位置
@SumeshTG我想加载相同的页面,但带有API的响应消息。我认为无需重新加载您的页面。您可以从success handl将数据设置为DOM元素