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.csdn.net/wangxiaohu__/article/details/7254598)
[2] JSONObject put,accumulate,element的區別(http://ljhzzyx.blog.163.com/blog/static/3838031220126810430157/)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章