页面之间json数据传递

来源:互联网 发布:flac ape 播放软件 编辑:程序博客网 时间:2024/06/05 00:44

这个项目是我在原有ssm项目的基础上完成的,如果对框架有不清楚的,可以看我之前的文章,不过json应该普通项目也能用,页面和后台传json通过jQuery的ajax来实现。整个项目我打包放在文章末尾了。

导入Json所需Jar包

Json所需jar包

在网页中引用js文件

<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-3.2.1.min.js"></script>

编写后台文件

这里只贴出用到的,整体项目可以到文章末尾下载。

@RequestMapping("/index/load")    private @ResponseBody List<User> requestJson(@RequestBody Map<String, Object> map){        List<User> list = userService.getAll();        return list;    }

编写js代码段

我这边将json使用ajax的方法写成了独立方法,之后可以写到独立js文件中,便于其他地方调用。

<script type="text/javascript">function myfunction(){    var html = "";    $.postJSON("<%=request.getContextPath()%>/index/load",{"id":1},function(e){        if(e){            for(var i=0;i<e.length;i++){                html+="name"+e[i].name+"id"+e[i].id;            }alert(html);            $("#show").html(html);        }    });}$.postJSON = function(url, data, callback) {    return jQuery.ajax( {        'type' : 'POST',        'url' : url,        'contentType' : 'application/json;charset=UTF-8',        'data' : JSON.stringify(data),        'dataType' : 'json',        'success' : callback    });};</script>

最后贴出项目地址
http://download.csdn.net/download/qq_31962349/9896592