问题描述
我需要将数据从在 http://localhost/index.htm 上运行的单个网页发送到在 http://localhost:8080/contactus/saveMessage 上运行的 servlet。 提交表单,数据由服务器(使用 POST 的 Spring 控制器)发送并保存在数据库中,该控制器返回一个简单的 String 消息以显示在原始网页上。 但是,我没有收到显示在表单下方的短信,而是使用下一个 URL 重新加载了网页:http://localhost/index.htm?fullName=Juan+Lopez&email=xxx%40yyy.com
代码如下:
<form id="messageForm">
<p><input class="w3-input w3-padding-16" type="text" maxlength="40" placeholder="Full Name *" required name="fullName"></p>
<p><input class="w3-input w3-padding-16" type="email" maxlength="50" placeholder="Email *" required name="email"></p>
<button class="w3-button w3-light-grey w3-padding-large" type="submit" onclick="sendMessageForm();">Send Message</button>
<p id="responseText"></p>
</form>
function sendMessageForm() {
const formData = new FormData(document.getElementById("messageForm"));
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("responseText").innerHTML = xhr.responseText;
document.getElementById("messageForm").reset();
} else {
document.getElementById("responseText").innerHTML = "Ocurrio un error al enviar su mensaje. " + this.responseText;
}
};
xhr.open("POST","http://localhost:8080/contactus/saveMessage",true);
xhr.send(formData);
}
控制器在“http://localhost:8080/contactus/saveMessage”上运行,它的代码是下一个:
@Controller
@RequestMapping(path = ContactMessageWebController.ROOT)
public class ContactMessageWebController {
public final static String ROOT = "/contactus";
private final ContactMessageService contactMessageService;
public ContactMessageWebController(ContactMessageService contactMessageService) {
this.contactMessageService = contactMessageService;
}
@CrossOrigin
@PostMapping("/saveMessage")
@ResponseBody
public String createContactMessage(@RequestParam(name = "fullName") String fullName,@RequestParam(name = "email") String email) {
contactMessageService.create(fullName,email);
return "ok";
}
}
为什么我没有得到控制器的“ok”响应而只是更新
带有 id="responseText" 的 p 标签
。 为什么我用这个 URL 重新加载页面:http://localhost/index.htm?fullName=Juan+Lopez&email=xxx%40yyy.com
提前致谢。
解决方法
如有必要,可以应用多种解决方案。但我相信第一个对你有用。
- 将按钮类型从
compilerOptions
替换为submit
button
- 表单
<button type="button" onclick="sendMessageForm();">Send Message</button>
返回错误
onsubmit
- 在表单提交事件中应用防止默认
<form id="messageForm" onsubmit="return false;">