日期:2014-05-16  浏览次数:20335 次

springmvc 使用json传递数据

需要使用的框架

spring3.0

jquery(简化ajax开发的js库)

fastjson(操作json的超级轻量级框架,方便,简单,灵活,提供json对象和字符串、java引用对象、集合、数组之间的转换)

Jackson(json处理器)

?

1.Control类

import java.io.IOException;

import java.io.PrintWriter;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

/**

* 根据班级ID查询教师

* 输出json格式的对象集合,Ajax实现

* @author:qiuchen

* @createTime:2012-6-14

* @param teacherName

* @return

*/

@RequestMapping("/findTeaByCls")

public ModelAndView findTeacherByCls(int clsId,HttpServletRequest request, HttpServletResponse response){

List<Teacher> tempList = new ArrayList<Teacher>();

//根据班级ID查询教师列表

List<Teacher> teacherList = this.teacherService.findByClsId(clsId);

//封装id和name属性

for (Teacher t : teacherList) {

t.setClassesList(null);

tempList.add(t);

}

//创建JSON对象

JSONObject object = new JSONObject(); ?

? ? object.put("tList",teacherList);

? ? //设置响应类型

? ? response.setContentType("text/Xml;charset=gbk");

? ? PrintWriter writer = null;

? ? try {

//获取输出流

writer = response.getWriter();

writer.print(object.toString());

} catch (IOException e) {

e.printStackTrace();

} finally{

if(writer != null){

writer.close();

}

}

? ? return null;

}

?

2.JS

/*

* 查询班级的老师

*/

function findTeaByCls(clsId){

document.getElementById("teacher").innerHTML = "";

var url = "${ctx}/manage/teacher/findTeaByCls.do?clsId="+clsId;

$.ajax({type:"POST", url:url,dataType:"text", success:function(datas) {

var l = datas;

//eval()函数计算出tList是json对象(========纠结============)

var a = eval('('+l+')');

/*

* alert(l);

* alert(a);

* alert(a.tList.length);

* alert(a.tList[0].id);

* alert(a.tList[0].name);

*/

for(var i=0,size=a.tList.length;i<size;i++){

document.getElementById("teacher").innerHTML += a.tList[i].name+"