javascript - 使用 jQuery 将用户输入从 html 表转换为 JSON

标签 javascript jquery json

我能够将预先填充的数据表转换为 JSON对象与 jQuery.这是代码:

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>jason@example.com</td>
            <td>Developer</td>
        </tr>
        <tr>
            <td>ted</td>
            <td>ted@example.com</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>

我尝试使用 .submit() jQuery 的方法使其工作,但我收到语法错误:

$('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);
);

我应该如何更改代码才能使其正常工作?

最佳答案

发生这种情况是因为 td 中没有文本。您需要找到输入的值。

1) 您需要在td中获取输入

2) 您需要获取 value of the input

另请尝试查看 editable div

试试这个:

row[rowName] = $(this).find('input').val();

关于javascript - 使用 jQuery 将用户输入从 html 表转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32316646/

相关文章:

javascript - React Bootstrap 全屏 Prop 不起作用

javascript - 为什么 Internet Explorer 9 不会对此单击事件使用react? [里面有简短的 jsFiddle 代码]

jquery - 悬停图像按钮以获得最快结果的最佳方法是什么 - CSS、jQuery

javascript - 如何正确解释作为字符串接收的 JSON 对象?

javascript - 编码后如何编辑 JSON 数组

javascript - AngularJS错误 "element.children(...).slideToggle is not a function"

jquery - 使用cheerio在没有 child 的 parent 中获取文本

javascript - 拒绝执行脚本,因为 MIME 类型 ('text/html' )不可执行,并且启用了严格的 MIME 类型检查

python - 如何将 BeautifulSoup 标签转换为 JSON?

javascript - 如何在 Yii2 中重新加载引导模式弹出窗口?