java和js中json数据使用小结

  在java中使用json数据需导入相应的jar包,即将相应的jar包复制到Web工程下 WebRoot–>WEB-INF–>lib文件夹中,相应的jar包为以下几个:
  这里写图片描述
下载地址:
1. Download json-lib(https://sourceforge.net/projects/json-lib/files/json-lib/)
2. Download ezmorph(https://sourceforge.net/projects/ezmorph/files/)
3. Download commons-logging(http://commons.apache.org/logging/download_logging.cgi)
4. Download commons-lang(http://commons.apache.org/lang/download_lang.cgi)
5. Download commons-collections(http://commons.apache.org/collections/download_collections.cgi)
6. Download commons-beanutils(http://commons.apache.org/beanutils/download_beanutils.cgi)
  不想一个个分别去下载的,在这里下载

前端js中:

function getFormData() 
{
    var json = 
    {
        "username" : document.getElementById("username").value
        , "pwd" : document.getElementById("pwd").value
    };
    return json;
}

function post()
{
    $.getJSON("./JsonTestServlet", {jsonData: JSON.stringify(getFormData())}, function(jsonData) 
    {
        alert(JSON.stringify(jsonData));
        alert(jsonData[0].username);
        alert(jsonData[0].pwd);
    });
}

  前端先将表单数据封装成json数据,再采用jquery封装的ajax技术传送json数据。

后台java中:

JSONObject jsonData = JSONObject.fromObject(request.getParameter("jsonData"));  //获取前端的jsonData
JSONArray jsonArray = new JSONArray();
String username = jsonData.getString("username");  // 获得前端传来的用户名

while (rs.next())
{
    JSONObject temp = new JSONObject().element("username", rs.getString("user")).element("pwd", rs.getString("pwd"));  // 创建临时json对象
    jsonArray.add(temp);  //将该json对象添加到jsonArray中
}
out.print(jsonArray.toString()); //将jsonArray对象传到前端

参考资料

[1] JSON.parse()和JSON.stringify()(http://blog.youkuaiyun.com/wangxiaohu__/article/details/7254598)
[2] JSONObject put,accumulate,element的区别(http://ljhzzyx.blog.163.com/blog/static/3838031220126810430157/)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值