1.controller将数据封装成json格式返回页面

@RequestMapping("/dataList")
public void datalist(CsoftCunstomerPage page,HttpServletResponse response) throws Exception{
List<CsoftCunstomer> dataList = csoftCunstomerService.queryByList(page);
//设置页面数据
Map<String,Object> jsonMap = new HashMap<String,Object>();
jsonMap.put("total",page.getPager().getRowCount());
jsonMap.put("rows", dataList); try {
//设置页面不缓存
response.setContentType("application/json");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
PrintWriter out= null;
out = response.getWriter();
out.print(JSONUtil.toJSONString(jsonMap));
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
} }

2.ajax提交数据以json格式到controller中

例一:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"> <html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<!--<script type="text/javascript" src="../static/js/jquery-1.7.2.min.js"></script>-->
<!--JS的地址可以写成下面这样,将来部署的时候,这些静态文件就可以单独部署了,不依赖于后台路径-->
<script type="text/javascript" src="http://localhost:8080/sshdemo/static/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
ajaxRequest();
}); function ajaxRequest() {
$.ajax({
url: "http://localhost:8080/sshdemo/hello/ajax",
type: "POST",
dataType: "json",
data: {
"a": ,
"b": ,
"c":
},
async: false,
success: function(data) {
alert("success");
$.each(data, function(index, element) {
alert(element.a);
alert(element.b);
alert(element.c);
});
},
error: function() {
alert("error");
}
});
}
</script>
</head>
<body>
<div>Hello World!</div>
</body>
</html>

实例二

package com.xbs.ready.ssh.controller;

import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; /**
*
* @author xbs
*/
@Controller
@RequestMapping("hello")
public class HelloController { /**
* ajax请求不需要返回页面,只需要得到response中的数据即可,所以方法签名为void即可
*
* @param request
* @param response
*/
@RequestMapping(value = "ajax", method = RequestMethod.POST)
public void ajaxDatas(HttpServletRequest request, HttpServletResponse response) {
String jsonResult = getJSONString(request);
renderData(response, jsonResult);
} private String getJSONString(HttpServletRequest request) {
//故意构造一个数组,使返回的数据为json数组,数据更复杂些
List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
Map<String, Object> map1 = new HashMap<String, Object>();
//可以获得ajax请求中的参数
map1.put("a", request.getParameter("a"));
map1.put("b", request.getParameter("b"));
map1.put("c", request.getParameter("c"));
datas.add(map1);
//故意构造一个数组,使返回的数据为json数组,数据更复杂些
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("a", "");
map2.put("b", "");
map2.put("c", "");
datas.add(map2);
String jsonResult = JSON.toJSONString(datas);
return jsonResult;
} /**
* 通过PrintWriter将响应数据写入response,ajax可以接受到这个数据
*
* @param response
* @param data
*/
private void renderData(HttpServletResponse response, String data) {
PrintWriter printWriter = null;
try {
printWriter = response.getWriter();
printWriter.print(data);
} catch (IOException ex) {
Logger.getLogger(HelloController.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (null != printWriter) {
printWriter.flush();
printWriter.close();
}
}
}
}

例二:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>helloworld</title>
<script type="text/javascript" src="/spring_mvc/js/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#testButton").click(function(){
var $a = $(this);
$.ajax({
url:"/spring_mvc/testAjax.do",
type:'post',
data:'name=admin&password=123456',
dataType:'html',
success:function(data,status){
if(status == "success"){
var objs = jQuery.parseJSON(data);
var str = "";
for(var i=;i<objs.length;i++){
str = str + objs[i].activityName+" ";
}
$("#content").html(str);
}
},
error:function(xhr,textStatus,errorThrown){
}
});
});
});
</script>
</head>
<body>
<button id="testButton">异步传输</button>
<div id="content"></div>
</body>
</html>

例三:

@RequestMapping("/dataList")
public void datalist(CsoftCunstomerPage page,HttpServletResponse response) throws Exception{
List<CsoftCunstomer> dataList = csoftCunstomerService.queryByList(page);
//设置页面数据
Map<String,Object> jsonMap = new HashMap<String,Object>();
jsonMap.put("total",page.getPager().getRowCount());
jsonMap.put("rows", dataList); try {
//设置页面不缓存
response.setContentType("application/json");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
PrintWriter out= null;
out = response.getWriter();
out.print(JSONUtil.toJSONString(jsonMap));
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
} }

ajax 与springmvc交互返回数据的更多相关文章

  1. ajax请求和aspx返回数据

    ajax请求: $(function () {            $.ajax({                url: "index.aspx?method=send",  ...

  2. SpringMvc在返回数据之前进行统一处理

    这里其实有多种解决方案 如果你不需要获取request对象 可以采用aop(环绕通知)的方式来统一修改 如果你需要获取request对象,那么就需要采用下面的方式 0自己定义一个注解,内容如下 @Ta ...

  3. jQuery的ajax请求express服务器返回数据

    html页面 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...

  4. 使用Ajax向SpringMVC传递Json数据

    这篇文章已经过时了. 请参考比较合适的前后端交互方式. 1.保证SpringMVC配置成功了. 2.在pom.xml中追加Jackson相关的依赖 <dependency> <gro ...

  5. Jquery Ajax 调用后台并返回数据

    一.前台调用ajax并解析json对象. $.ajax({ url : '', type : 'POST', //GET data : '’, beforeSend : function(reques ...

  6. ajax中的后台返回数据data的意义

  7. ajax返回数据为undefined

    在使用ajax异步请求后台返回数据后,使用console.log(data.message)打印返回数据,显示为undefined.苦恼了很久,终于在网上找到了答案. 先给大家看下异步代码: /*清零 ...

  8. Ajax中返回数据的格式

    Ajax中常见的返回数据的格式有三种:分别为文本,XML和JSON 返回的文本格式我们在上一堂课Ajax基础介绍中已经介绍过了 Ajax.php Form.html:通过Ajax对象的response ...

  9. 02 - Unit01:服务器返回数据的json处理+搭建项目环境

    服务器返回数据的json处理+搭建项目环境 服务器返回数据的json处理 springMVC JSP响应流程 请求 -->DispatcherServlet -->HandlerMappi ...

随机推荐

  1. VisualStudio:如何监控 ADO.NET?

    背景 很多场景下我们都需要监控 ADO.NET,如:查看某些框架(ORM)生成的 SQL.如何在不能使用 SQL Profile 的情况下监控 SQL 呢?VS 为我们提供了一个工具,本文做一些介绍! ...

  2. Lua的文件操作

    先简单介绍一下被迫使用Lua的IO的情境: 游戏支持玩家自定义上传头像,在排行榜中会显示玩家列表(包括本服.跨服),原有的做法是先检测CCUserDefault中是否存在指定图片的key以及它的状态. ...

  3. md5目录下的文件包括子目录

    find ./ -type f -print0 | xargs -0 md5sum

  4. java 生成zip文件并导出

    总结一下,关于Java下载zip文件并导出的方法,浏览器导出. String downloadName = "下载文件名称.zip"; downloadName = Browser ...

  5. [Android] Implementation vs API dependency

    原文链接: https://jeroenmols.com/blog/2017/06/14/androidstudio3/ https://blog.csdn.net/lonewolf521125/ar ...

  6. [Web 前端] CSS 盒子模型,绝对定位和相对定位

    cp : https://blog.csdn.net/web_yh/article/details/53239372 一.盒子模型: 标准模式和混杂模式(IE).在标准模式下浏览器按照规范呈现页面:在 ...

  7. C#与Java 的区别

    相同点:都是面向对象编程的语言,都能够实现面向对象的(封装,继承,多态)思想 不同点:1.   c#中的命名空间是namespace类似于Java中的package(包),在Java中导入包用impo ...

  8. HTTPS安全证书介绍

    IIS配置web SSL 安全证书Https访问 From : http://cao416451347ming.blog.163.com/blog/static/1154556162010217441 ...

  9. Springmvc的handler method参数绑定常用的注解

    转自:http://blog.longjiazuo.com/archives/1149   1. 简介: handler method参数绑定常用的注解,我们根据他们处理的Request的不同内容部分 ...

  10. git如何上传所有的新文件 gitlab如何上传所有的新文件 git本地覆盖服务器 强制本地覆盖服务器

    原文地址:  https://blog.csdn.net/qq_28093585/article/details/78749153 目的描述:新建的git项目,项目中有许多要从本地上传到git仓库的新 ...