(一)后台向前台传送map形式的数据,前台获取Map对象形式显示在页面上:
首先在页面上传递一个参数
在jsp页面中:
function test01(){
//路径
var JsonUrl = "<%=basePath%>selectPexamByPIDQuestionsByMap?PID=3";
$.ajax({
url:JsonUrl,
type:'get',
dataType:'json',
success:function(data){
var array = new Array();
//遍历,先获取,然后map在array中是栈,先进后出,因此pop出来。
$.each(data,function(i,val){
array.push(val);
});
var q1 = JSON.stringify(array.pop());
var q2 = JSON.stringify(array.pop());
alert(q1);//弹出数据。
},
error:function(data){
alert("ajax error");
}
});
}
在springmvc的controller中:
//返回一个借口,这里是提取试卷考卷的方法
@ResponseBody
@RequestMapping("/selectPexamByPIDQuestionsByMap")
//http://localhost:8888/CourseOnlineProject///selectPexamByPID?PID=8
public Map
//2.查找所有根据ID查找,以map格式返回
List
//Map
Map
for(int i=0;i
System.out.println("questionsList.get("+i+").getQuestionstype().getQtype()"+questionsList.get(i).getQuestionstype().getQtype());
String typeName = questionsList.get(i).getQuestionstype().getQtype();
if(map.containsKey(typeName)){
List
qList.add(questionsList.get(i));
map.put(typeName, qList);
}else{
List
qList.add(questionsList.get(i));
map.put(typeName, qList);
}
}
return map;//以map形式传递给前台
}
当在浏览器输入: //http://localhost:8888/CourseOnlineProject///selectPexamByPID?PID=8
时候,就会获取到数据如下:(json形式)
{"选择题":[{"qid":"Q0417645","qquesttion":"岁数大编译JavaApplication源程序文件将产生相应的字节码文件,这些字节码文件的扩展名为()。","qchoose":"A.java B.class C..html D.exe ","qrightAnswer":"A","qscore":2}],"判断题":[{"qid":"Q0260198","qquesttion":"简答题是对是错","qchoose":"A. 错 B.对","qrightAnswer":"A","qscore":6},{"qid":"Q0260198","qquesttion":"简答题是对是错","qchoose":"A. 错 B.对","qrightAnswer":"A","qscore":6},{"qid":"Q5182661","qquesttion":"简答题是对是错","qchoose":"A. 错 B.对","qrightAnswer":"A","qscore":6},{"qid":"Q5207134","qquesttion":"简答题是对是错","qchoose":"A. 错 B.对","qrightAnswer":"A","qscore":6}]}而同时,在打开页面的时候,会弹出数据:
(二)通过ajax像后台传送单个对象
首先在jsp页面中,写一个简单的测试demo:
" value="submit"/>
在controller中:
@Controller
@RequestMapping(value="/test")
public class TestController0530 {
@ResponseBody
@RequestMapping(value="/test01",method=RequestMethod.POST)
public String test01(@ModelAttribute Student s){
System.out.println(s.getSno()+"--"+s.getSname());
return "success";
}
这时候,在后台显示: