通过new FormData提交简单数据
- 效果示例图
- 代码
效果示例图
代码
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title><style type="text/css">* {padding: 0px;margin: 0px;box-sizing: border-box;}input,input:focus {border-radius: 4px;outline: none;padding: 0px 12px;}input::placeholder,input::-moz-placeholder,input::-webkit-input-placeholder {color: #999;}.form-wrap {width: 600px;margin: 12px auto;}.form-item {display: flex;flex-direction: row;align-items: center;margin-bottom: 12px;}.form-item-label {width: 100px;}.form-item-content {--width: 100px;width: calc(100% - var(--width));display: flex;flex-direction: row;align-items: center;}.form-item-content input[type='text'] {border: 1px solid #dcdcdc;width: 100%;height: 40px;}.form-item-content input[type='radio'] {border: 1px solid #dcdcdc;width: 20px;height: 20px;margin-left: 12px;cursor: pointer;}.form-item-content label {margin-left: 12px;}.form-footer {width: 100%;display: flex;flex-direction: row;padding-left: 100px;}.form-btn {border: 1px solid #00a2ef;border-radius: 8px;width: 100px;height: 40px;margin-right: 12px;cursor: pointer;}</style></head><body><form class="form-wrap" id="myForm" name="myForm"><div class="form-item"><label class="form-item-label">姓名:</label><div class="form-item-content"><input type="text" name="username" value="" /></div></div><div class="form-item"><label class="form-item-label">年龄:</label><div class="form-item-content"><input type="text" name="userAge" value="" /></div></div><div class="form-item"><label class="form-item-label">性别:</label><div class="form-item-content"><label for="woman">女</label><input id="woman" type="radio" name="userSex" value="0" /><label for="man">男</label><input id="man" type="radio" name="userSex" value="1" /></div></div><div class="form-item"><label class="form-item-label">孩子one:</label><div class="form-item-content"><input type="text" name="children[0][name]" value="" /></div></div><div class="form-item"><label class="form-item-label">年龄one:</label><div class="form-item-content"><input type="text" name="children[0][age]" value="" /></div></div><div class="form-item"><label class="form-item-label">孩子two:</label><div class="form-item-content"><input type="text" name="children[1][name]" value="" /></div></div><div class="form-item"><label class="form-item-label">年龄two:</label><div class="form-item-content"><input type="text" name="children[1][age]" value="" /></div></div><div class="form-footer"><button class="form-btn" type="reset">重置</button><button class="form-btn" id="submitBtn">提交</button></div></form></body><script type="text/javascript">document.querySelector("#submitBtn").addEventListener("click", (e) => {//阻止事件向上冒泡e.preventDefault();const myForm = document.querySelector("#myForm");const formData = new FormData(myForm);const formJson = Object.fromEntries(formData.entries());console.log("[]", formJson)})</script>
</html>