美文网首页
不用jsp怎么实现前后端交互?给萌新后端的ajax教程(3)

不用jsp怎么实现前后端交互?给萌新后端的ajax教程(3)

作者: 少年弈 | 来源:发表于2020-04-27 12:53 被阅读0次

    Hello大家好,今天为大家带来ajax系列的(大概可能也许是)最后一篇,这一篇我们主要讲讲前端html页面接收json后可以做的处理。
    一、遍历json
    (1)List型
    Controller代码:
    @RequestMapping(value = "/test")
    public @ResponseBody List<String> testAJAX(HttpServletRequest request, HttpServletResponse response) {
    List <String> QAQ=new ArrayList<>();
    QAQ.add("你好啊!");
    QAQ.add("两只老虎跑得快!");
    QAQ.add("Hello World.");
    return QAQ;
    }
    前端代码:
    function testajax() {
    var text=document.getElementById("txt").value;
    .ajax({ url:"test", type:"post", data:{}, dataType:"json", async:true, success:function(data){ alert(data[0]); alert(data[1]); alert(data[2]); }, }); } 打开浏览器,你会发现依次跳出三个弹窗,是我们添加到List中的数据,也就是说,遍历List型json用类似于数组下标的方式。 当然我们每次都手写下标太麻烦了,用一个for循环来解决,把success中的内容换成: for(var i=0;i<data.length;i++) { alert(data[i]); } 代码正常运行喔。 (2)Map型 Controller函数: @RequestMapping(value = "/test") public @ResponseBody Map<String,String> testAJAX(HttpServletRequest request, HttpServletResponse response) { Map<String,String> a=new HashMap<>(); a.put("topic","我是标题"); a.put("context","我是内容"); return a; } 前端:.ajax({
    url:"test",
    //contentType:"application/json;charset=UTF-8",
    type:"post",
    data:{},
    dataType:"json",
    async:true,
    success:function(data){
    alert(data.topic);
    alert(data.context);
    },
    });
    也就是说,使用data.key的名字就可以访问value啦。
    你自己封装好的对象也符合这条规则喔。
    (3)Map型List
    什么是Map型List呢?就是多个Map的集合。
    Controller函数:
    @RequestMapping(value = "/test")
    public @ResponseBody List<Map<String,String>> testAJAX(HttpServletRequest request, HttpServletResponse response) {
    Map<String,String> a=new HashMap<>();
    a.put("topic","我是标题a");
    a.put("context","我是内容a");
    Map<String,String> b=new HashMap<>();
    b.put("topic","我是标题b");
    b.put("context","我是内容b");
    List<Map<String,String>> c=new ArrayList<>();
    c.add(a);
    c.add(b);
    return c;
    }
    前端:
    $.ajax({
    url:"test",
    //contentType:"application/json;charset=UTF-8",
    type:"post",
    data:{},
    dataType:"json",
    async:true,
    success:function(data){
    alert(data[0].topic);
    alert(data[0].context);
    alert(data[1].topic);
    alert(data[1].context);
    },
    });
    当然同样可以使用for循环的写法。
    可是为什么要闲的蛋疼这样写呢?我来举一个例子,比如我们写一个博客项目,我们定义一个对象Article,它里面有发表时间time属性,还有标题topic属性。当我们需要加载文章列表时,如果列表想显示文章的标题和发表时间,就需要这么做,List<Article>就是这种形式。
    二、使用json传递数据,后端给前端发送Date,前端收到的不是标准格式的时间而是一串数字的问题。
    在domain层Date类型数据的get方法上方加上
    @JsonFormat(pattern ="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    注解即可。
    三、结语
    基于jQuery的ajax教程暂时告一段落,如果有什么遗漏的地方过后会再开一篇文章进行补充。感谢阅读,希望能对你有所帮助。

    相关文章

      网友评论

          本文标题:不用jsp怎么实现前后端交互?给萌新后端的ajax教程(3)

          本文链接:https://www.haomeiwen.com/subject/adsywhtx.html