serializeArray() 方法序列化表单元素(类似 .serialize() 方法),返回 JSON 数据结构数据。
html代码:
<form> <div><input type="text" name="a" value="1" id="a" /></div> <div><input type="text" name="b" value="2" id="b" /></div> <div><input type="hidden" name="c" value="3" id="c" /></div> <div> <textarea name="d" rows="8" cols="40">4</textarea> </div> <div><select name="e"> <option value="5" selected="selected">5</option> <option value="6">6</option> <option value="7">7</option> </select></div> <div> <input type="checkbox" name="f" value="8" id="f" /> </div> <div> <input type="submit" name="g" value="Submit" id="g" /> </div> </form>
jquery代码:
$('form').submit(function() { console.log($(this).serializeArray()); return false; });
将产生以下数据结构(浏览器提供的console.log
):
[ { name: "a", value: "1" }, { name: "b", value: "2" }, { name: "c", value: "3" }, { name: "d", value: "4" }, { name: "e", value: "5" } ]
实际应用例子,通过ajax把表单数据上传给服务器:
var formdataArr = $(form).serializeArray(); var formdata = {}; for (var i = 0; i < formdataArr.length; i++) { if(formdataArr[i]['name'] == "editorValue"){ continue; } formdata[formdataArr[i]['name']] = formdataArr[i]['value']; }; $.ajax({ url: '/cases/submit', type: 'post', dataType: 'json', data: formdata, success: function(data){ if(data.r == "0"){ bootbox.alert({ message: data.msg || "恭喜,提交保存成功", callback: function() { document.location.href = "/cases/showCaseList"; } }); return false; }else{ bootbox.alert(data.msg || "抱歉,提交保存失败"); return false; } }, error: function(){ bootbox.alert("抱歉,网络繁忙,请稍后再试"); } });