springboot搭建ajax请求显示Charts图形

  • 2019 年 12 月 12 日
  • 筆記

背景

前端与后端交互的时候通常是直接请求,但直接交互会影响用户体验,通过异步方式进行与后端服务交互是不错的简单技术,Ajax是一个比较不错的异步请求,网上也有很多,但是还是想自己学习下,下面简单演示一个请求,一方面方便自己复习,二方面给大家积累小小知识。

正常请求图

效果

数据响应完全依赖后端服务响应,如果服务端出现异常现象,或者出现短路,或者前端显示空白,或者闪频等现象很影响用户体验,那么小范围或者局部刷新是一个必然产生的技术。

Ajax请求图

说明:

  • 前端输入数据通过jquery/dom等技术获取数据;
  • Ajax通过get/post把数据提交个后端服务器
  • 服务器响应结果给ajax,ajax再回显到页面或者通过转发到其他页面

java演示

  • 新建springboot工程,选择导入依赖jar
  • 新建统一返回结果类

统一响应类

import java.util.HashMap;import java.util.Map;  /** * @author liwen * @Title: Msg * @Description: 响应数据 * @date 2019/12/4 / 11:07 */public class Msg {    /**状态码   100-成功    200-失败*/    private int code;    /**提示信息*/    private String msg;      /**用户要返回给浏览器的数据*/    private Map<String, Object> extend = new HashMap<String, Object>();      public static Msg success(){        Msg result = new Msg();        result.setCode(100);        result.setMsg("处理成功!");        return result;    }      public static Msg fail(){        Msg result = new Msg();        result.setCode(200);        result.setMsg("处理失败!");        return result;    }      public Msg add(String key,Object value){        this.getExtend().put(key, value);        return this;    }     //省越get}

AjaxControler类

@PostMapping("/cookice")    @ResponseBody    public Msg getCookie(String cookie) {        if (!StringUtils.isEmpty(cookie.trim())) {            //做回显数据用            HashMap<String, String> demokinfo = new HashMap<>();              demokinfo.put("cooke", cookie);           demokinfo.put("ok", "我是java");            return Msg.success().add("page", demokinfo);        } else {              String oo = "{"calculable": true,"title": {"text": "某楼盘销售情况","subtext": "纯属虚构"},"toolbox": {"feature": {"mark": {"show": true,"title": {"markUndo": "删除辅助线","markClear": "清空辅助线","mark": "辅助线开关"},"lineStyle": {"color": "#1e90ff","type": "dashed","width": 2}},"dataView": {"show": true,"title": "数据视图","readOnly": false,"lang": ["数据视图","关闭","刷新"]},"magicType": {"show": true,"title": {"bar": "柱形图切换","stack": "堆积","tiled": "平铺","line": "折线图切换"},"type": ["line","bar","stack","tiled"]},"restore": {"show": true,"title": "还原"},"saveAsImage": {"show": true,"title": "保存为图片","type": "png","lang": ["点击保存"]}},"show": true,"padding": 20},"tooltip": {"trigger": "axis"},"legend": {"data": ["意向","预购","成交"]},"xAxis": [{"type": "category","boundaryGap": false,"data": ["周一","周二","周三","周四","周五","周六","周日"]}],"yAxis": [{"type": "value"}],"series": [{"smooth": true,"name": "成交","type": "line","itemStyle": {"normal": {"areaStyle": {"type": "default"}}},"data": [10,12,21,54,260,830,710]},{"smooth": true,"name": "预购","type": "line","itemStyle": {"normal": {"areaStyle": {"type": "default"}}},"data": [30,182,434,791,390,30,10]},{"smooth": true,"name": "意向","type": "line","itemStyle": {"normal": {"areaStyle": {"type": "default"}}},"data": [1320,1132,601,234,120,90,20]}]}";              //前端显示数据           HashMap<String, String> hashMap = new HashMap<>();            hashMap.put("infodemo", oo);              return Msg.fail().add("key", hashMap);        }      }

前端写法

给html绑定事件为:submit_cookie():改函数可以随便写

显示:

Post参考代码

 $(function () {        //去首页        submit_cookie();    });      function submit_cookie() {        //获取cookie值        var cookie = $("#cookieinfo").val();        var keyChart99 = echarts.init(document.getElementById('maintp9'));          $.ajax({                url: "/cookice",                data: {"cookie": cookie},                type: "post",                 //回调函数                success: function (result) {                    if (result.code == 100) {                         console.log("响应结果数据:" + result.extend.key);                        // 使用刚指定的配置项和数据显示图表。                       console.log("响应结果数据:" + result.extend.page.ok);                        //回显数据                        $("#cookieinfo").val(result.extend.page.cooke);                      } else {keyChart99.setOption(JSON.parse(result.extend.page.key));                       console.log("响应结果数据:" + result.extend.key.infodemo);                    }                }            });        } else {            console.log("cookie为空");        }}

前端页面显示:

回顾

  • 本次采用jquery.js的ajax请求并回显数据
  • 需要声明

$(function () {

//编写函数

});

  • 函数写法
$(function () {      //去首页      submit_cookie();  });  function submit_cookie() {})

Get参考代码

//当点击在线用例编辑就请求function to_init() {    $.ajax({        type: 'GET',        url: '/xmind/ajaxData',        data: {"ids": 1},        beforeSend: function () {            loadingIndex = layer.msg('处理中', {icon: 16});        },        success: function (result) {            layer.close(loadingIndex);            if (result.code == web_status.SUCCESS) {                layer.msg("信息打开成功", {time: 1000, icon: 6}, function () {                    console.log("显示xmind数据:" + userXmind);                });            } else {                layer.msg("信息打开失败,请重新操作", {time: 2000, icon: 5, shift: 6}, function () {                  });            }          }    });}

总结:

上面是简单ajax的get/post请求,相信大家了解,其实在做性能明白ajax原理与写法,对自己理解前端性能有一定帮助,上面如果不明白可以百度查询相关资料。