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. 【Devops】【docker】【CI/CD】1.docker搭建Gitlab环境

    CI/CD[持续化集成/持续化交付] docker搭建Gitlab环境 1.查询并拉取gitlab镜像 docker search gitlab docker pull gitlab/gitlab-c ...

  2. Windows 同一时候开启核心显卡与独立显卡(不接显示器启动核芯显卡)

    採用Mp4视频压缩格式编码时,非常耗CPU.所以决定上显卡.进行显卡加速.选择了Intel核心显卡进行视频编码加速,效果非常理想.但如今的问题是:在PC上如何同一时候开启核心显卡与独立显卡.经过几番周 ...

  3. C#零基础入门07:打老鼠之面向对象重构

    一:前言 有了上面两节的知识,尤其是第六节之后,现在我们回过头看我们的打老鼠游戏,我们是不是会发现:这个程序也太不面向对象了.我们所有的代码逻辑都分布在Code-Hide中(UI的后台代码,称之为Co ...

  4. Android Studio导入项目的中文注释乱码解决方法

           在Android studio中,导入Android的项目后,容易出现项目文件的中文乱码,中文无法正常显示,变成了一些格子问号之类的,导致无法查看中文的注释,下面来看看导入项目和解决乱码 ...

  5. warning: LF will be replaced by CRLF in dubbo-demo-api/pom.xml.

    今天使用git add .的时候出现了一个错误. 错误如下: 解决方案: $ rm -rf .git // 删除.git $ git config --global core.autocrlf fal ...

  6. aspnet_regiis -i VS 20XX 的开发人员命令提示符

    1,VS 2010 Setting environment x86 tools. D:\Program Files\Microsoft Visual Studio 10.0\VC>aspnet_ ...

  7. vue使用watch 观察路由变化,重新获取内容

    watch: { $route(to) { console.log(to) if (to.path.indexOf('index') != -1) { //路由变化后重新获取帖子列表 this.$ht ...

  8. GDB 程序调试简单实践

    用了好久的GCC/G++ 却一直都没用过GDB调试过程序,有时程序不是非常大,一般有错,直接看编译器编译结果就几乎相同知道错在哪儿了,或者使用codeblocks单步调试,甚至回到windows以下调 ...

  9. Mahout源码目录说明

    http://www.cnblogs.com/dlts26/archive/2011/08/23/2150230.html mahout项目是由多个子项目组成的,各子项目分别位于源码的不同目录下,下面 ...

  10. 理解MySQL数据库覆盖索引 (转)

    http://www.cnblogs.com/zl0372/articles/mysql_32.html 话说有这么一个表: CREATE TABLE `user_group` ( `id` int( ...