首页 > 解决方案 > 如何停止在javascript中提交表单?

问题描述

我首先使用 fetch API 获得 json 对象的响应。然后我想检查一下 json.exist == true。如果为真,我希望表单停止发送并打印出错误消息。但是,每次 json.exist == true 时,它​​似乎都会出现。我该如何解决?

  document.indexform.addEventListener("submit", async (e) => {
  messages =[]
  user = {"username" : "123"}
  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(user),
  };

  const response = await fetch("/username",options)
  const json = await response.json()

  if(json.exist == true){
    messages.push("Username already exists")
  }

  if(messages.length > 0){
    e.preventDefault()
    errorElement.innerHTML = messages.join(',')
  }

});

标签: javascripthtmljsonformsasync-await

解决方案


我会尝试不同的方法。

e.preventDefault()

在您的函数顶部,然后在满足您的条件时使用 javascript 提交表单

if (json.exist !== true){
    document.forms["myform"].submit();
}

推荐阅读