javascript - 如何停止在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(',')
}
});
解决方案
我会尝试不同的方法。
放
e.preventDefault()
在您的函数顶部,然后在满足您的条件时使用 javascript 提交表单
if (json.exist !== true){
document.forms["myform"].submit();
}
推荐阅读
- python-3.x - 在Django中查询相同模型时如何返回两个不同的错误消息
- cypress - 如何禁用赛普拉斯日志悬停?
- html - 为什么我的图像在使用百分比时消失,而在使用像素时出现?
- c# - 使用 .Net Core 在 PowerShell 中安装 ActiveDirectory 驱动器时遇到问题
- css - 如何在 Parcel bundler 中动态加载 css 文件?
- c# - 如何查找输入类型文本的 id,如果不存在则将其添加到 c-#
- ruby - W: Lint/Void: Lital <<-DOC 在 void 上下文中使用
- c# - Excel VSTO C# - 创建 ListObject 的 VSTO 对应项会中断重命名
- c# - 从 Azure Active Directory 访问具有授权类型的用户
- java - 如何在 groovy spock 中模拟 Autowired 构造函数依赖项