前端開發中,將 <form> 表單資料自動轉為 JSON 格式提交至後端,是常見需求。jQuery 提供的 .serializeArray() 可快速實現,但輸出的是陣列格式,需進一步轉換為標準 JSON 物件。
<form action="" method="post" id="tf">
<table>
<tr>
<th>姓名:</th>
<td><input type="text" id="txtUserName" name="model.UserName" /></td>
<th>聯系手機:</th>
<td><input type="text" name="model.Mobile" id="txtMobile" maxlength="11" /></td>
<th>密碼:</th>
<td><input type="password" name="model.Pwd" id="txtPwd" maxlength="11" /></td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="button" value=" 提 交 " name="butsubmit" id="butsubmit" />
</td>
</tr>
</table>
</form>
$(function () {
$('#butsubmit').click(function () {
// 1. 序列化為陣列 [{name: 'model.UserName', value: '...'}, ...]
var data = $('#tf').serializeArray();
// 2. 轉換為標準 JSON 物件 { "model.UserName": "...", ... }
var jsonData = {};
$.each(data, function(i, field) {
jsonData[field.name] = field.value;
});
// 3. 發送 AJAX 請求
$.post('/home/ratearticle', jsonData, RateArticleSuccess, 'json');
});
});
function RateArticleSuccess(result) {
alert(result.UserName + result.Mobile + result.Pwd);
}
public JsonResult RateArticle(UserInfo model)
{
return Json(model);
}
若 name 屬性採用 model.UserName 這類點號命名,後端模型繫結器通常能自動映射到巢狀物件屬性。若需前端直接產生巢狀 JSON,可擴充套件 $.fn.serializeObject:
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) o[this.name] = [o[this.name]];
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
// 使用方式
var jsonData = $('#tf').serializeObject();
serializeArray() 會忽略未勾選項目,後端需預設值處理。serializeArray() 不支援 <input type="file">,需改用 FormData。$.post 預設 application/x-www-form-urlencoded,若後端要求 application/json,請用 $.ajax 並設定 contentType。