javascript - Spring Boot获取复选框值

标签 javascript java spring thymeleaf

类问题:

class question{
          private String questionContent;
          private String questionId;
          private List<String> options;
     }

我的json数据:

[{'questionContent': 'content1', 'options': ['a', 'b', 'c', 'd'], 'questionId': '001'},
 {'questionContent': 'content2', 'options': ['a', 'b', 'c', 'd']}, 'questionId': '002']

我使用 fastjson 创建一个列表

List<Question> questionList = JSON.parseArray(jsonData, Question.class);

使用 thymeleaf 创建复选框:

<form>
<div th:each="question : ${questionList}">
    <div>
        <label th:text="${question.questionContent}"></label>
    </div>
    <div th:each="question2 : ${question.Options}">
        <input class="options" th:name="${question.questionId}"
         type="checkbox" th:value="${question2}">
    </div>
</div>
</form>

spring boot如何获取checkbox的值? Controller 如何实现? 或者ajax发布数据?

最佳答案

您可以使用 Jquery 将数据以 json 形式手动提交到后端的 REST POST 端点。 你可以按照你喜欢的任何方法进行操作。在这种情况下,我所做的是在提交表单时触发 jquery 表单提交,并使用 ajax 向其余 Controller 发出 POST 请求。这里,我假设一组特定的复选框只会选中一个复选框。否则您必须对其进行修改。

使用 Jquery :

$(document).ready(function() {
$( "form" ).submit(function() {
  event.preventDefault();

 var questions;
 questions = {}; 
 $.each($("input[type='checkbox']:checked"),function(){
   var questionName,questionValue;
   questionValue = $(this).val();
   questionName = $(this).attr('name')
   questions[questionName] = questionValue;
 });

$.ajax({
type : 'POST',
contentType : "application/json;charset=utf-8",
url : '/endpoint/questions/save',
data : JSON.stringify(questions),
dataType : 'json',              
success : function(data) {

        }
    });
});
});

还有一个休息端点,例如:

@RestController
@RequestMapping("/endpoint/questions")
public class QuestionsController {

    @Autowired
    private QuestionsService service;

    @PostMapping
    @RequestMappint("/save")
    @ResponseStatus(HttpStatus.CREATED)
    public Long create(@RequestBody Questions resource) {
        Preconditions.checkNotNull(resource);
        return service.create(resource);
    }
}

关于javascript - Spring Boot获取复选框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729747/

相关文章:

javascript - 如何从 Node js 创建 Twilio channel

Javascript - 替换字符串文字中的转义字符

java - 使用类路径从 Eclipse 中导出 jar ...你是怎么做到的?

java - 在 Spring Boot 的同一个 pom.xml 中管理 H2 和 Postgres

java - 多个否定的配置文件

javascript - 如何只重新加载一张图像

javascript - Meteor:获取要在子模板上使用的数据

java - 数字 EditText 暂时显示文本键盘(输入连接无效)

java - EditText 如何占据布局中的所有剩余空间?

java - 如何使用spring消息PropertyPlaceholderConfigurer传递参数?