前端获取后端传来的foreach然后将foreach中的数据传送
2020-05-14 本文已影响0人
printf200
前端
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; Charset=gb2312">
<meta http-equiv="Content-Language" content="zh-CN">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<title>试卷</title>
<link rel="shortcut icon" href="../images/Logo_40.png" type="image/x-icon">
<!--Layui-->
<link href="${pageContext.request.contextPath}/resource/layui-v2.5.5/css/layui.css" rel="stylesheet" />
<!--font-awesome-->
<link href="${pageContext.request.contextPath}/resource/font-awesome/css/font-awesome.min.css" rel="stylesheet" />
<!--全局样式表-->
<link href="${pageContext.request.contextPath}/resource/css/global.css" rel="stylesheet" />
<!-- 比较好用的代码着色插件 -->
<link href="${pageContext.request.contextPath}/resource/css/prettify.css" rel="stylesheet" />
<!-- 本页样式表 -->
<link href="${pageContext.request.contextPath}/resource/css/detail.css" rel="stylesheet" />
</head>
<body>
<!-- 导航 -->
<%@include file="common/header.jsp"%>
<!-- 主体(一般只改变这里的内容) -->
<div class="blog-body">
<div class="blog-container">
<blockquote class="layui-elem-quote sitemap layui-breadcrumb shadow">
<a href="${pageContext.request.contextPath}/student/index" title="网站首页">网站首页</a>
<a href="${pageContext.request.contextPath}/student/paper" title="试卷中心">试卷中心</a>
</blockquote>
<div class="blog-main">
<div class="blog-main-left">
<div class="layui-form layuimini-form">
<div class="layui-form-item">
<div class="article-detail shadow">
<div class="article-detail-title">
${vm.name}
</div>
<div class="layui-input-block">
<input type="text" name="id" required lay-verify="required" value="${vm.id}" autocomplete="off" class="layui-input id" style="display: none">
</div>
<div class="article-detail-content">
<c:forEach items="${vm.titleItems}" var="title">
<h2>${title.name}</h2>
<c:forEach items="${title.questionItems}" var="question" varStatus="status">
<form id="${question.itemOrder}">
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">${question.itemOrder}</label>
<input type="text" name="itemOrder" required lay-verify="required" value="${question.itemOrder}" autocomplete="off" class="layui-input" style="display: none" id="${question.id}">
<div class="layui-input-block">
<h4>${question.title}</h4>
</div>
</div>
<div class="layui-form-item layui-form-text">
<div class="layui-input-block">
<textarea name="content" placeholder="请输入内容" class="layui-textarea" id="${question.id}" form="${question.itemOrder}" ></textarea>
</div>
</div>
</form>
</c:forEach>
</c:forEach>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit lay-filter="saveBtn">提交</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--遮罩-->
<div class="blog-mask animated layui-hide"></div>
<!-- layui.js -->
<script src="${pageContext.request.contextPath}/resource/layui-v2.5.5/layui.js"></script>
<!-- 自定义全局脚本 -->
<script src="${pageContext.request.contextPath}/resource/js/global.js"></script>
<!-- 比较好用的代码着色插件 -->
<script src="${pageContext.request.contextPath}/resource/js/prettify.js"></script>
<!-- 本页脚本 -->
<script src="${pageContext.request.contextPath}/resource/js/detail.js"></script>
<script>
layui.use(['form','table'], function () {
var form = layui.form,
layer = layui.layer,
table = layui.table,
$ = layui.$;
table.render();
//监听提交
form.on('submit(saveBtn)', function (data,index) {
var id = $('.id').val();
// var itemOrder = $('#itemOrder').val();
var ids=[];
$("form").each(function(i){
var id = this.id;
ids.push(id);
});
//获取答案
// var contents=[];
var answerItems = [];
for (var i=0;i<ids.length;i++) {
var obj = document.getElementById(ids[i]).getElementsByTagName("textarea");
for (var j = 0; j < obj.length; j++) {
if (obj[j].value.length > 0) {
var answerItem =
{
content:obj[j].value,
itemOrder:obj[j].form.id,
questionId:obj[j].id
};
answerItems.push(answerItem);
// contents.push(obj[j].value);
}
}
}
// var content = contents.join(",");
//获取questionid
// var questionIds = [];
// $("textarea").each(function () {
// var id = this.id;
// questionIds.push(id);
//
// });
// var questionId = questionIds.join(",");
// var filed = data.field;
var answer = {
id:id,
answerItems:answerItems
};
// content:content,questionId:questionId
// {id:id,answerItems:JSON.stringify(answerItems)}
$.ajax({
url:'${pageContext.request.contextPath}/examPeper/answerSubmit',
type:'post',
data:JSON.stringify(answer)
// ,dataType : 'json'
,contentType : "application/json"
,success:function (res) {
var datajson = eval("(" + res + ")");
var code = datajson.code;
layer.alert('答卷得分:'+datajson.data, {
skin: 'layui-layer-molv' //样式类名
,closeBtn: 0
}, function(){
location.href="${pageContext.request.contextPath}/student/index";
});
},
error:function () {
layer.msg("修改失败")
}
});
});
// return false;
});
</script>
</body>
</html>
后台获取foreach遍历数据代码
var ids=[];
$("form").each(function(i){
var id = this.id;
ids.push(id);
});
//获取答案
// var contents=[];
var answerItems = [];
for (var i=0;i<ids.length;i++) {
var obj = document.getElementById(ids[i]).getElementsByTagName("textarea");
for (var j = 0; j < obj.length; j++) {
if (obj[j].value.length > 0) {
var answerItem =
{
content:obj[j].value,
itemOrder:obj[j].form.id,
questionId:obj[j].id
};
answerItems.push(answerItem);
// contents.push(obj[j].value);
}
}
}
传送json数据
//具体看以上代码
var answer = {
id:id,
answerItems:answerItems
};
// content:content,questionId:questionId
// {id:id,answerItems:JSON.stringify(answerItems)}
$.ajax({
url:'${pageContext.request.contextPath}/examPeper/answerSubmit',
type:'post',
data:JSON.stringify(answer) // 用于后台接受json数据
// ,dataType : 'json'
,contentType : "application/json"
,success:function (res) {
var datajson = eval("(" + res + ")");
var code = datajson.code;
layer.alert('答卷得分:'+datajson.data, {
skin: 'layui-layer-molv' //样式类名
,closeBtn: 0
}, function(){
location.href="${pageContext.request.contextPath}/student/index";
});
},
error:function () {
layer.msg("修改失败")
}
});
});
image.png
后端
/**
* 答卷
* @param examPaperSubmitVM
* @return
*/
@RequestMapping("/answerSubmit")
public void answerSubmit(@RequestBody ExamPaperSubmitVM examPaperSubmitVM, HttpSession session, HttpServletResponse response,HttpServletRequest request) throws IOException {
User user = (User) session.getAttribute("userinfo");
Map map = new HashMap();
ExamPaperAnswerInfo examPaperAnswerInfo = examPaperAnswerService.calculateExamPaperAnswer(examPaperSubmitVM, user);
if (null == examPaperAnswerInfo) {
map.put("code",1);
map.put("msg", "试卷不能重复做");
response.getWriter().println(JSONObject.toJSONString(map));
}
ExamPaperAnswer examPaperAnswer = examPaperAnswerInfo.getExamPaperAnswer();
Integer userScore = examPaperAnswer.getUserScore();
String scoreVm = ExamUtil.scoreToVM(userScore);
Date now = new Date();
ExamPaper examPaper = examPaperAnswerInfo.getExamPaper();
List<ExamPaperQuestionCustomerAnswer> examPaperQuestionCustomerAnswers = examPaperAnswerInfo.getExamPaperQuestionCustomerAnswers();
examPaperAnswerService.insertByFilter(examPaperAnswer);
examPaperQuestionCustomerAnswers.stream().filter(a -> QuestionTypeEnum.needSaveTextContent(a.getQuestionType())).forEach(d -> {
TextContent textContent = new TextContent(d.getAnswer(), now);
textContentService.insertByFilter(textContent);
d.setTextContentId(textContent.getId());
d.setAnswer(null);
});
List<ExamPaperQuestionCustomerAnswer> examPaperQuestion = new ArrayList<>();
for (ExamPaperQuestionCustomerAnswer examPaperQuestionCustomerAnswer:examPaperQuestionCustomerAnswers) {
examPaperQuestionCustomerAnswer.setExamPaperAnswerId(examPaperAnswer.getId());
examPaperQuestion.add(examPaperQuestionCustomerAnswer);
}
examPaperQuestionCustomerAnswerService.insertList(examPaperQuestion);
switch (ExamPaperTypeEnum.fromCode(examPaper.getPaperType())) {
default:
break;
}
map.put("code",0);
map.put("msg","提交成功");
map.put("data",scoreVm);
response.getWriter().println(JSONObject.toJSONString(map));
}