问题
- ajax取来的json 一个个往表单上赋值 费时费力一个不好还搞错
分析
- 是不是可以批量赋值减少录入出错呢,这里用的jquery毕竟有个好的方法.serializeArray() ,得到结果我只要遍历一下就动态赋值了
方法
- 就几行代码,但inputname要与json中的属性对应
<body>
<form id="frm">
<input type="text" id="id1" name="id1">
<input type="text" id="id2" name="id2">
<select type="text" id="id3" name="id3">
<option value=1>a</option>
<option value=2>b</option>
</select>
<input type="text" id="id4" name="id4">
<input type="text" id="id5" name="id5">
</form>
<button onclick="fnGet()">获取form表单数据</button>
<button onclick="fnSet()">给from表单赋值</button>
</body>
<script>
function fnGet() {
let arrObj = $("#frm").serializeArray();
let resultJson = {}
arrObj.forEach(o => {
resultJson[o.name] = o.value
})
console.log(resultJson)
}
function fnSet() {
let obj = {
"id1": "aa",
"id2": "bb",
"id3": "1",
"id4": "cc",
"id5": "dd"
}
for (let o in obj) {
document.getElementsByName(o)[0].value = obj[o]
}
}

