如何将复选框值从 HTML 发送到 Node JS

How to send checkboxes values from HTML to Node JS?

本文关键字:Node JS HTML 复选框      更新时间:2023-09-26

我试图将一些复选框值从HTML发送到Node JS。在我的 HTML 文件中,我在表格中有一些复选框。我得到了如下选中的复选框值,

$("#createSS").click(function (event) {
    event.preventDefault();
    var searchIDs = $("#imgTable input:checkbox:checked").map(function () {
        return $(this).val();
    }).get();
    console.log("selected::::" + searchIDs);
});

我的HTML表单是,

<form action="/addSlideShow" method="POST">
    <table id="imgTable" class="table">
        {{#images}}
            <tr>
                <td><input id={{imgURL}} type="checkbox" name="ch" value={{imgURL}}/></td>
            </tr>
        {{/images}}
    </table>
    <input id="createSS" type="submit" value="Create Slide Show" class="btn btn-success pull-left" disabled/>&nbsp;&nbsp;
</form>

在节点 JS 中,

app.post('/addSlideShow', function (req, res) {
    var $ = req.body;
    $('td').each(function () {
        console.log($(this).text());
    });
});

当我在 HTML 中单击按钮时,for 不会提交。我该如何解决这个问题?

提前感谢!

这是因为

您没有将数据发布到表单 url。由于您使用了永远不会提交的event.preventDefault(),也没有使用$.ajax()发布数据

尝试使用 ajax 发布数据,例如,

$("#createSS").click(function (event) {
    event.preventDefault();
    var searchIDs = $("#imgTable input:checkbox:checked").map(function () {
        return $(this).val();
    }).get();
    console.log("selected::::" + searchIDs);
    $.ajax({
       url:'/addSlideShow',type:'post',
       data:{searchid:searchIDs},
       success:function(response){
          console.log(response);
       }
    });
});

在节点js中,你会得到,

app.post('/addSlideShow', function(req, res) {
    console.log(req.body); //Output=> like { searchid: 'Array of checked checkbox' }
    console.log(req.body.searchid); // to get array of checked checkbox
});
<input id="createSS" type="submit" value="Create Slide Show" class="btn btn-success pull-left" disabled/>

您的提交按钮已禁用。最后删除该disabled属性。

您正在使用event.preventDefault(),它告诉浏览器不要在单击时执行该执行的操作。删除该行,您的表单将被提交。我不是 Node 忍者,但您在 req.body 中的数据不会采用 html 格式。查询 $("td") 是前端逻辑。您需要为每个复选框分配不同的名称,例如name="ch-{{$index}}"(在角度ng-repeat中也是如此)。或者你应该通过ajax发送{searchid: searchIDs}