我有以下JavaScript代码,我得到一个错误,上面写着:
未捕获的类型错误:无法读取未定义的"的属性"value";
具体来说,在以下行:const parola=form.parola.value;
<%- include('partials/header') %>
<form action="/signup">
<h2>Kullanıcı Oluştur</h2>
<label for="email">email</label>
<input type="text" name="email" required/>
<div class="email error"></div>
<label for="email">Parola</label>
<input type="password" name="email" required/>
<div class="password error"></div>
<button type="submit">Oluştur</button>
</form>
<%- include('partials/footer') %>
<script>
const form=document.querySelector('form');
form.addEventListener('submit',async (e)=>{
e.preventDefault();
const email=form.email.value;
const parola=form.parola.value;
// console.log(email,parola);
try {
const res=await fetch('/signup',{
method:'POST',
body:JSON.stringify({email,parola}),
headers:{'Content-Type':'application/json'}
});
} catch (error) {
console.log(error);
}
});
</script>
有什么建议吗?
您可以使用FormData:
<form action="/signup">
<h2>Kullanıcı Oluştur</h2>
<label for="email">email</label>
<input type="text" name="email" required/>
<div class="email error"></div>
<label for="email">Parola</label>
<input type="password" name="password" required/>
<div class="password error"></div>
<button type="submit">Oluştur</button>
</form>
<script>
function handleSubmit(e) {
e.preventDefault();
const formData = new FormData(e.target);
console.log('Object.fromEntries(formData)', Object.fromEntries(formData));
return Object.fromEntries(formData);
}
const form=document.querySelector('form');
form.addEventListener('submit',async (e)=>{
var formData = handleSubmit(e);
try {
const res=await fetch('/signup',{
method:'POST',
body:JSON.stringify(formData),
headers:{'Content-Type':'application/json'}
});
} catch (error) {
console.log(error);
}
});
</script>
工作演示:https://jsfiddle.net/cse20x61/3/
问题是document.querySelector
是HTMLElementObject
的结果,所以如果你想要你的电子邮件,你应该这样做:
form.querySelector('input[name=email]').value