微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

发布到另一台服务器时,AJAX 重新加载网页

如何解决发布到另一台服务器时,AJAX 重新加载网页

我需要将数据从在 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>

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

带有 id="responseText" 的 p 标签

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

提前致谢。

解决方法

如有必要,可以应用多种解决方案。但我相信第一个对你有用。

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

button

  1. 表单 <button type="button" onclick="sendMessageForm();">Send Message</button> 返回错误

onsubmit

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。