我知道很多次都会问这个问题,但是我想使用axios从表单提交数据到api但是当我点击提交按钮时它不起作用,它会清除然后将空字段提交给api。我知道有一个event.preventDefault()方法应该处理这个,但我不知道在我的代码中把它放在哪里。 这是我的代码:
window.onload = function submitData(){
const name = document.getElementById('name').value
const email = document.getElementById('email').value
const contacts = document.getElementById('contacts').value
const location = document.getElementById('location').value
const username = document.getElementById('username').value
const password = document.getElementById('password').value
axios.get('http://example.com/register', {
investorNames: name,
investorEmail: email,
investorContacts: contacts,
investorLocation: location,
username: username,
password: password
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
HTML
<form id='register-form'>
<input type="text" placeholder="name" required id="name">
<input type="email" placeholder="Email" required id="email">
<input type="contacts" placeholder="contacts" required id="contacts">
<input type="location" placeholder="location" required id="location" >
<input type="username" placeholder="username" required id="username">
<input type="password" placeholder="Password" required id="password">
<input class="button" name="submit" type="submit" value="submit" onclick="submitData()" />
</form>
从onload中删除submitData并将其声明为普通函数
function submitData(){}
并将输入类型从提交更改为按钮
<input class="button" name="submit" type="button" value="submit" onclick="submitData()" />
有用