日期:2014-05-19  浏览次数:20616 次

求一个ajax json jsp样例
如题 后台返回json数据 前台js进行接收 拼接jsp页面 有的发asdbench@qq.com谢谢!

------解决方案--------------------
探讨

我在jsp 改怎么来获取数据呢

------解决方案--------------------
/**
 * struts2 响应 ajax 请求,Json格式的
 *
 */
public class AjaxPrintUtil {
//编码格式
private static String encoding="gbk";
/**
* 向客户端输出字符串
* @param str
* @throws IOException
*/
public static final void printString(String str) throws IOException
{
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset="+encoding);
PrintWriter writer = response.getWriter();
writer.print(str);
writer.flush();
writer.close();
}
/**
* 向客户端输出对象
* @param o
* @throws IOException
*/
public static final void printObject(Object o) throws IOException
{
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset="+encoding);
JSONObject obj=JSONObject.fromObject(o);
PrintWriter writer = response.getWriter();
writer.print(obj.toString());
writer.flush();
writer.close();
}
/**
* 向客户端输出集合
* @param list
* @throws IOException
*/
@SuppressWarnings("unchecked")
public static final void printList(List list) throws IOException {
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset="+encoding);
JSONArray jsArray=JSONArray.fromObject(list);
PrintWriter writer = response.getWriter();
writer.print(jsArray);
writer.flush();
writer.close();
}
}

Action调用这个方法会以json格式输出到页面
AjaxPrintUtil.printList(list);//集合
AjaxPrintUtil.printObject(object);//对象
AjaxPrintUtil.printString(object);//集合

页面接收json
function aa(){
$.post(url,function(msg){
var Chats = eval("("+msg+")");//回调的数据
for()//遍历下就好了
})
}