ajax json 提交 java_Java中使用json与前台Ajax数据交互的方法

本文主要为大家分享了ajax获取显示json数据的一种方法,供大家参考,具体内容如下

1、首先前台用ajax,其中注意datatype一定要选择json方式,action成功返回给页面的json内容是这样的[{"number":"v006","names":"lilei"}],可见comment['names']对应"names":"lilei",comment['number']对应"number":"v006"。

$.ajax({

type: "post",

url:'apply/mystudent.action?',

cache: false,

datatype : "json",

success: function(data){

$.each(data, function(commentindex, comment){

alert("姓名"+ comment['names']);

alert("学号"+comment['number']);

});

}

});

2、ajax的url指向在java的action中mystudent方法,返回的list其实是一个对象student,包括了names和nunmber字段

public string mystudent() throws exception{

list list=priceservice.query();//调用接口实现类

this.jsonutil(list);

return null;

}

3、action页面专门写一个方法jsonutil来做为json方法

// 调用json工具方法,传入参数alist

public void jsonutil(object accountlist) throws exception {

httpservletresponse response = servletactioncontext.getresponse();

log.info("json格式:" + accountlist.tostring());

string returnjson = jsonconvert.returnjson(accountlist);

response.setcharacterencoding("utf-8");

response.getwriter().println(returnjson);

}

4、我用的是一种比较新的json包jackson

import java.io.stringwriter;

import org.codehaus.jackson.map.objectmapper;

public class jsonconvert {

static string jsonstr;

public static string returnjson(object object) throws exception{

objectmapper objectmapper = new objectmapper();

stringwriter stringwriter = new stringwriter();

objectmapper.writevalue(stringwriter, object);

jsonstr = stringwriter.tostring();

return jsonstr;

}

}

以上就是本文的全部内容,希望对大家的学习有所帮助。

希望与广大网友互动??

点此进行留言吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值