多个单选框的值传到后台

来源:互联网 发布:淘宝达人在哪里找 编辑:程序博客网 时间:2024/06/06 01:15

使用C标签的foreach循环将从后台拿到的值遍历到前台,单选框的name值不能相等就用对象的ID代替,设置一个隐藏域,在JS中将选中单选框的Value值拼接成json字符串,以form表单的形式提交到action层,action层中getParameter()方法通过隐藏域的name拿到value值。在service层将json字符串转为对象。传到数据库中。
jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><h1 align="center">问卷调查</h1>    <script type="text/javascript">    var i=0;</script><form id="investigate_form"><input type="hidden" id="investigateJson" name="investigateJson" >    <c:if test="${!empty questionList }">        <c:forEach items="${questionList }" varStatus="status" var="question">                <div>                    问题 ${status.index+1}:${question.question }                    <br>                     <input type="hidden" id="iqid_${status.index+1}" name=${question.id } value="123">                     <input name=${question.id } type="radio" value="optionA" />A:${question.optionA }                     <input name=${question.id } type="radio" value="optionB" />B:${question.optionB  }                    <br>                     <input name=${question.id } type="radio" value="optionC" />C:${question.optionC  }                    <input name=${question.id } type="radio" value="optionD" />D:${question.optionD  }                </div>                <script type="text/javascript">                i=i+1;            </script>           </c:forEach>    </c:if></form>

JS代码:

add : function() {            $('#investigate_dlg').dialog({                title : '填写调查问卷',                closed : true,                closable : false,                cache : false,                model : true,                width : 500,                height : 650,                href : basePath + '/investigate/add',                               onLoad : function() {                   },                buttons: [{                    text : "保存",                    iconCls : 'icon-ok',                                    handler : function() {                        var str="{";                            for(var m=1;m<=i;m++)                            {                            var iqi=$("#iqid_"+m).attr("name");                                                    var check=$("input[name="+iqi+"]:checked").val();                            if(m<i){                                str=str+'"'+iqi+'":"'+check+'",';                            }                            else{                                str=str+'"'+iqi+'":"'+check+'"';                                                        }                                       }                        str=str+"}";                        $("#investigateJson").val(str);                            $('#investigate_form').form({                            url : basePath+'/investigate/add/submit',                            onSubmit : function(){                                                                                          },                                                      success : function() {                                $('#investigate_dlg').dialog('close');                                $.messager.alert('信息提示','操作成功','info',function(){                                     $('#investigate_list').datagrid('reload');                                });                            },                            error : function() {                                $.messager.alert('信息提示','操作失败','info',function(){                                    $('#investigate_list').datagrid('reload');                                });                            },                        });                        $("#investigate_form").submit();                        /*var form = document.getElementById("investigate_form");                                               form.action = basePath+'/investigate/add/submit';                                               form.method="post";                        form.submit();                        */                    }                },                {                    text : "关闭",                    iconCls : 'icon-cancel',                    handler:function(){                        $('#investigate_dlg').dialog('close');                    }                               }]            })            $('#investigate_dlg').dialog('open');        }

action代码;

```@RequestMapping("/add/submit")    public String addsubmit(InvestigateAnswerModel investigateAnswerModel, HttpServletRequest request,            HttpServletResponse response) {        Object message = null;        try {            String investigateJson = request.getParameter("investigateJson");            investigateService.addInvestigate(investigateAnswerModel,investigateJson);            message = getOperateMessage(true);        } catch(Exception e){            e.printStackTrace();        }        return null;}

service层代码:

@SuppressWarnings("unchecked")    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)    public void addInvestigate(InvestigateAnswerModel investigateAnswer, String investigateJson) {        UserModel user = new UserModel();//创建一个user对象        user.setId("4028810a53cfa6030153cfa7a6a00002");//这个是固定了ID,可以改变的,将用户id写入对象中        InvestigateModel enves = new InvestigateModel();//创建一个调查问卷的对象        enves.setUser(user);//将用户对象放入调查问卷中,因为数据库中InvestigateModel与UserModel是多对一关系,所以InvestigateModel的userid即为该用户对象的ID        enves.setInvestigateTime(new Date());//将系统时间放入数据库        List<InvestigateAnswerModel> iaList = new ArrayList<InvestigateAnswerModel>();//创建一个问卷答案的List集合        //将前台传来的json字符串转化为map集合        Map<String, Object> map = null;        try {            map = new ObjectMapper().readValue(investigateJson, Map.class);        } catch (Exception e) {            e.printStackTrace();        }        //将数据传入数据库中        for (Entry<String, Object> entry : map.entrySet()) {            QuestionModel question = new QuestionModel();            question.setId(entry.getKey());            InvestigateAnswerModel ia = new InvestigateAnswerModel();            ia.setInvestigate(enves);            ia.setQuestion(question);            ia.setAnswer(entry.getValue());            iaList.add(ia);//将一个问卷答案对象放入集合中        }        enves.setIaList(iaList);//将该集合放入到调查问卷对象中        investigateDao.save(enves);//保存该对象到数据库中        // investigateAnswerDao.saveOrUpdasteAll(iaList);    }
0 0