我能夠使用jQuery將預先填充的表格與數據轉換爲JSON
對象。下面是代碼:使用jQuery將用戶輸入從html表格轉換爲JSON
var header = $('table thead tr th').map(function() {
return $(this).text();
});
var tableObj = $('table tbody tr').map(function (i) {
var row = {};
$(this).find('td').each(function (i) {
var rowName = header[i];
row[rowName] = $(this).text();
});
return row;
}).get();
JSON.stringify(tableObj);
和HTML表是這樣的:
<table>
<thead>
<tr>
<th>Name</th>
<th>E-mail</th>
<th>Job</th>
</tr>
</thead>
<tbody>
<tr>
<td>jason</td>
<td>[email protected]</td>
<td>Developer</td>
</tr>
<tr>
<td>ted</td>
<td>[email protected]</td>
<td>Bear</td>
</tr>
</tbody>
</table>
現在我的任務就是真正處理空白表格的用戶輸入。當用戶加載頁面時,表格是空的,沒有值,用戶在輸入並點擊提交後,我想將用戶輸入數據轉換爲JSON
對象並將其傳遞迴後端。
我試圖做到這一點由經線table
成form
,並添加<input>
標籤在每個<td>
,這樣的事情:
<form>
<table>
<tbody>
<tr>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
<tr>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
</tbody>
</table>
<button type="submit">Submit</button>
</form>
我嘗試使用從jQuery的的.submit()
方法使它工作,但我得到語法錯誤:
$('form').submit(
var header = $('table thead tr th').map(function() {
return $(this).text();
});
var tableObj = $('table tbody tr').map(function (i) {
var row = {};
$(this).find('td').each(function (i) {
var rowName = header[i];
row[rowName] = $(this).text();
});
return row;
}).get();
JSON.stringify(tableObj);
);
我應該如何更改我的代碼,使其工作?
你有沒有考慮過使用類似DataTables(http://www.datatables.net)的東西?使用JSON對象自動構建表並允許更多功能。 – jonmrich