我在 static/main.js 中有这个函数:
function getCookie(cookieName) {
const name = cookieName + "=";
const decodedCookie = decodeURIComponent(document.cookie);
const cookieArray = decodedCookie.split(';');
for (let cookie of cookieArray) {
while (cookie.charAt(0) == ' ') {
cookie = cookie.substring(1);
}
if (cookie.indexOf(name) == 0) {
return cookie.substring(name.length, cookie.length);
}
}
return "";
}
var UserDataGet = async (token) => {
const userRequest = await fetch(`/api/GetUserInfo?token=${token}`);
if (await userRequest.ok) {
const userData = await userRequest.json();
if (Object.keys(userData).length === 0) {
return "0";
} else {
return userData;
}
} else {
return "0";
}
};
var DataValidate = async () => {
if ( await UserDataGet(getCookie("token")) == "0") {
alert("you are not registred");
return false
}
else {
return true
}
}
这是形式:
<form method="POST" enctype="multipart/form-data" onsubmit = "return DataValidate()">
<label for="Message">Write your message</label>
<input name="Message" type="text">
<input name="TopicId" type="hidden" value="">
<input name="AuthToken" type="hidden" value="">
</form>
DataValidate() 函数检查用户是否已注册。如果不是,则返回 false,该函数本身可以正常工作。但是如何将 DataValidate() 函数的结果返回到表单呢?
现代从业者建议将请求逻辑移至 js(使用
fetch),因为这会将可视化与数据流处理分开。此外,您已经在页面上启用了 javascript。尽管形状选项很简约,可能更适合简单项目中需要简单形状的情况。取决于项目。您的表单正在提交,因为 DataValidate 函数是异步的,并且像任何异步函数一样返回Promise。 Promise 是一个对象,而对象是一个始终转换为 true 的真值。也就是说,您的函数始终返回一个被视为 true 的值。
至于您的代码,这是一个工作版本(使用SubmitEvent对象取消事件):
从
在
从
在