AJAX 在 post 到另一台服务器时重新加载网页

AJAX reloads web page when post to another server

我需要从 http://localhost/index.htm 上的单个网页 运行 将数据发送到 http://localhost:8080/[= 上的 servlet 运行 31=]。 提交表单后,服务器(Spring 使用 POST 的控制器)发送数据并将其保存在数据库中,并且此控制器 returns 显示在原始网页上的简单字符串消息。 但是,我没有收到显示在表格下方的短信,而是使用下一个 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>

调用下一个 javascript 代码:

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”响应而只是更新

p tag with id="responseText"

。 为什么我用这个 URL 重新加载页面:http://localhost/index.htm?fullName=Juan+Lopez&email=xxx%40yyy.com

提前致谢。

多个解决方案可以根据需要全部套用。但我相信第一个对你有用。

  1. 将按钮类型从 submit 替换为 button

<button type="button" onclick="sendMessageForm();">Send Message</button>

  1. 形式onsubmitreturn假

<form id="messageForm" onsubmit="return false;">

  1. 在表单提交事件中应用防止默认值

$("#messageForm").submit(function(e) { e.preventDefault(); });