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. arcgispro字段计算器

    使用python语法 在python中没有类似sub()或者subString()的方法,但是字符串的截取操作却是更加简单. 只需要把字符串看作是一个字符数组,截取子串非常方便. 多余的话就不啰嗦了, ...

  2. 动态规划经典问题Java实现

    动态规划问题Java实现 如果我们有面值为1元.3元和5元的硬币若干枚,如何用最少的硬币凑够11元? public class DPProblem { public static void main( ...

  3. 广告狂人第一至七季/全集Mad Men迅雷下载

    广告狂人 第一季 Mad Men Season 1 (2007) 本季看点:你是谁?你想要什么?你爱乾什么?这些都不重要,重要的是你怎么把东西卖出去.凡是了解纽约的人都知道,今天,在麦迪逊大道(Mad ...

  4. ios之CABasicAnimation

    博主:最近iOS开发中用到CoreAnimation的framework来做动画效果,虽然以前也用过,但一直没有系统学习过,今天看到一篇非常详细的博文(虽然是日语,但真的写的很好),在此翻译出来供大家 ...

  5. 配置SSD-caffe测试时出现“Check failed: error == cudaSuccess (10 vs. 0) invalid device ordinal”解决方案

    这是由于GPU数量不匹配造成的,如果训练自己的数据,那么我们只需要将solver.prototxt文件中的device_id项改为自己的GPU块数,一块就是0,两块就是1,以此类推. 但是SSD配置时 ...

  6. Netty Associated -- Channel

    A nexus to a network socket or a component which is capable of I/O operations such as read, write, c ...

  7. BZOJ3328: PYXFIB

    题目:http://www.lydsy.com/JudgeOnline/problem.php?id=3328 题解:关键在于只处理i%k的项,那么我们就需要用一个式子来表达这个东西. p%k==1. ...

  8. 用SLF4j/Logback打印日志-1

    在 浅谈后端日志系统 中已经写了很多日志方面的零散的非技术的东西.本篇更像一份入门说明,讲解一下SLF4j/Logback.SLF4J是一套抽象的日志API接口,logback它是的底层实现,所以在这 ...

  9. 混沌分形之谢尔宾斯基(Sierpinski)

    本文以使用混沌方法生成若干种谢尔宾斯基相关的分形图形. (1)谢尔宾斯基三角形 给三角形的3个顶点,和一个当前点,然后以以下的方式进行迭代处理: a.随机选择三角形的某一个顶点,计算出它与当前点的中点 ...

  10. windows包管理器chocolatey

    1.安装chocolatey打开cmd.exe执行@powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((New-Obj ...