繁体   English   中英

使用javascript innerHtml中的thymeleaf将数据传递到Spring Boot控制器

[英]Pass data to spring boot controller using thymeleaf from javascript innerHtml

我将在javascript中创建表格行,在表格行中我有一些输入字段,现在我想使用百里香从该字段访问数据

function myCreateFunction2() {
        var table = document.getElementById("mdlTable2");
        var row = table.insertRow(1);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);
        var cell4 = row.insertCell(3);
        var cell5 = row.insertCell(4);
        var cell6 = row.insertCell(5);
        cell1.innerHTML = "Item";
        cell2.innerHTML = '<input id="item" type="number" value="">';
        cell3.innerHTML = "UOM";
        cell4.innerHTML = '<textarea></textarea>';
        cell5.innerHTML = '<button type="submit" value="save" class="btn btn-success btn-sm" onclick="save()">Save</button></form>';
        cell6.innerHTML = '<button type="button" class="btn btn-danger btn-sm" onclick="myDeleteFunction2()">Remove</button>';

    }

您需要为每个输入添加一个name ,然后在控制器上询问这些参数。 假设您期望url为/edit

JS

function myCreateFunction2() {
        var table = document.getElementById("mdlTable2");
        var row = table.insertRow(1);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);
        var cell4 = row.insertCell(3);
        var cell5 = row.insertCell(4);
        var cell6 = row.insertCell(5);
        cell1.innerHTML = "Item";
        cell2.innerHTML = '<input id="item" type="number" value="" name="id">';
        cell3.innerHTML = "UOM";
        cell4.innerHTML = '<textarea id="description" name="description"></textarea>';
        cell5.innerHTML = '<button type="submit" value="save" class="btn btn-success btn-sm" onclick="save()">Save</button></form>';
        cell6.innerHTML = '<button type="button" class="btn btn-danger btn-sm" onclick="myDeleteFunction2()">Remove</button>';
    }

控制者

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String edit(@RequestParam("id") String id,
                   @RequestParam("description") String description { ... }

保存(JS)

现在,由于您没有表单,因此如果要提交数据,则需要一个表单。 在这种情况下,我们将使用javascript做到这一点。

function save() {

    // First, let's create the form.
    var form = document.createElement("form");
    form.method = "POST";
    form.action = "/edit";

    // Now, let's add the inputs.
    var id = document.getElementById('id');
    var description = document.getElementBy('description');
    form.appendChild(id);
    form.appendChild(description);

    // Submit the form.
    document.body.appendChild(form);
    form.submit();

}

另一种更简单的方法是将html代码包装为表单。 当然,由于需要编辑和删除表单,因此您需要复制代码。

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM