ajax与controller之间传输数据

最近在学习ajax,顺便记录一下。本篇记录是ajax与controller之间传输数据。

首先实现后端给前端传输json数据。如下图在这里插入图片描述

controller


  @RequestMapping("/ExamLessonlist")
    @ResponseBody  // 用于转换对象为json
    public List<ExamLesson> list(){
        List<ExamLesson> list =  examLessonService.findExamLesson();
        return list;
    }
    

@ResponseBody
@ResponseBody是作用在方法上的,@ResponseBody 表示该方法的返回结果直接写入 HTTP response body 中,一般在异步获取数据时使用【也就是AJAX】,在使用 @RequestMapping后,返回值通常解析为跳转路径,但是加上 @ResponseBody 后返回结果不会被解析为跳转路径,而是直接写入 HTTP response body 中。 比如异步获取 json 数据,加上 @ResponseBody 后,会直接返回 json 数据。@RequestBody 将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。

service


@Service
public class ExamLessonServiceImpl implements ExamLessonService {
    //属性注入
    @Autowired
    private ExamLessonMapper examLessonMapper;
    @Override
    public List<ExamLesson> findExamLesson() {

        return examLessonMapper.findExamLesson();
    }
    

Mapper


<mapper namespace="com.example.mapper.ExamLessonMapper">
    <select id="findExamLesson"   resultType="com.example.pojo.ExamLesson" >
    select id,lessonname from lesson
  </select>
</mapper>
    

到这里后端就完成了json数据的传输,接下来就是前端ajax请求。

前端


<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="static/easyui/jquery.min.js"></script>
    <script type="text/javascript" src="static/easyui/jquery.easyui.min.js"></script>

    <script type="text/javascript">
        $(function(){
            $.ajax({
                url:"ExamLessonlist",
                type:"post",
                dataType:"json",
                success:function(data){
                  for(var v in data){
                      console.log(data[v].id);
                      console.log(data[v].lessonname);
                  }
                },
                error:function(error){
                    alert(error);
                }
            })
        })
    </script>
</head>
<body>
123
</body>
</html>
    

实现的效果
在这里插入图片描述


版权声明:本文为qq_36470898原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。