我正在使用XMLHttpRequest构建一个表单。这是我的问题:
当表单提交并且响应为0(字符串)时,#output div中显示的消息是“出了问题.”(必须如此);
相反,当表单提交并且响应为1(字符串)时,#output div中显示的消息是"1“,而不是”发送!“(应该是这样)。
<form id="contactform">
<input name="name" type="text">
<input name="surname" type="text">
<input name="email" type="text">
<input type="submit" value="Send">
</form>
<div id="output"></div>
JS
const form = document.getElementById("contactform");
const output = document.getElementById("output");
form.onsubmit = () => {
var xhr = new XMLHttpRequest();
var formData = new FormData(form);
xhr.open('POST', 'https:...');
xhr.send(formData);
xhr.onreadystatechange = () => {
if (this.readyState === 4 && this.status === 200) {
showResponse(this.response);
}
};
xhr.onerror = () => {
showResponse("0");
};
return false;
};
showResponse = data => {
var text;
switch (data) {
case "0":
text = "Something went wrong...";
break;
case "1":
text = "SENT!";
break;
default:
text = data;
}
output.innerHTML = text;
};
我的密码怎么了?
发布于 2019-05-18 13:51:53
this
引用问题,更改如下:
form.onsubmit = () => {
var xhr = new XMLHttpRequest();
var formData = new FormData(form);
xhr.open('POST', 'https:...');
xhr.send(formData);
xhr.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
showResponse(this.response);
}
};
xhr.onerror = () => {
showResponse("0");
};
return false;
};
https://stackoverflow.com/questions/56199416
复制相似问题