getElementById获取输入值为空,POST空对象问题求助
问题:提交表单时DOM无法获取输入值,返回空对象
提交企业信息(公司名称、联系人姓名等)时,填写输入框内容后DOM无法获取到值,提交的对象始终为空,结构如下:
- adress: ""
- companyName: ""
- contactName: ""
- contactTitle: ""
表单代码
<form> <div class="form-group"> <label for="">Company Name</label> <input type="text" class="form-control" id="companyName" placeholder="Company Name!" /> </div> <div class="form-group"> <label for="">Contact Name</label> <input type="text" class="form-control" id="contactName" placeholder="Contact Name!" value="" /> </div> <div class="form-group"> <label for="">Contact Title</label> <input type="text" class="form-control" id="contactTitle" placeholder="Contact Title!" /> </div> <div class="form-group"> <label for="">Country</label> <input type="text" class="form-control" id="inputCountry" placeholder="Country!" /> </div> </form>
JavaScript代码
'use strict'; let inputCompanyName = document.getElementById('companyName'); let inputContactName = document.getElementById('contactName'); let inputContactTitle = document.getElementById('contactTitle'); let country = document.getElementById('inputCountry'); const btnSubmit = document.getElementById('submit'); let newCompany = { companyName: inputCompanyName.value, contactName: inputContactName.value, contactTitle: inputContactTitle.value, adress: country.value, }; btnSubmit.addEventListener('click', e => { e.preventDefault(); axios .post('https://northwind.vercel.app/api/suppliers', newCompany) .then(res => { console.log('Response', res.data); alert('Success!'); }); });
已尝试过innerHTML、innerText以及表单method属性,均无法解决问题。
解决方案
问题核心:newCompany对象在页面加载完成时就被初始化了,此时输入框还没有任何用户输入,所有值都是空字符串。后续用户填写内容后,这个对象并不会自动更新。
需要把获取输入值的逻辑移到提交按钮的点击事件内部,每次点击提交时才读取输入框的当前值,这样就能获取到用户填写的内容了。
修改后的JavaScript代码:
'use strict'; let inputCompanyName = document.getElementById('companyName'); let inputContactName = document.getElementById('contactName'); let inputContactTitle = document.getElementById('contactTitle'); let country = document.getElementById('inputCountry'); const btnSubmit = document.getElementById('submit'); btnSubmit.addEventListener('click', e => { e.preventDefault(); // 每次点击时才创建包含最新输入值的对象 let newCompany = { companyName: inputCompanyName.value, contactName: inputContactName.value, contactTitle: inputContactTitle.value, adress: country.value, }; axios .post('https://northwind.vercel.app/api/suppliers', newCompany) .then(res => { console.log('Response', res.data); alert('Success!'); }); });
补充:也可以直接在事件里通过document.getElementById重新获取元素的值,不需要提前保存变量,效果一致。
内容的提问来源于stack exchange,提问作者Jarl X
相关产品推荐
相关产品推荐

