首先,我在某处读到我们不应该使用 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/