關於java接收前臺$.ajax格式爲多維json數組數據爲null的原因及解決方法

前言

最近在使用java接收前臺$.ajax數據格式爲多維json數組數據時,遇到了一個問題,問題例子如下:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="jquery-1.7.2.js"></script>
    <script>
        //前臺代碼如下
        $(document).ready(function(){
            $('#btn').click(function(){
                //obj爲多維json數組數據格式
                var obj={
                    name:'key',
                    age:18,
                    sex:'男',
                    info:{
                        qq:'123456',
                        email:'[email protected]',
                        girlFriend:{
                            name:'lucy',
                            age:18,
                            sex:'女'
                        }
                    }
                };
                $.ajax({
                    type:'post',
                    url:'Test',
                    data:obj,
                    dataType:'json',
                    success:function(data){
                        console.log(data);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">按鈕</button>
</body>
</html>

後臺java代碼如下:

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        System.out.println(request.getParameter("name"));//key
        System.out.println(request.getParameter("age"));//18
        //一維數據如:name、age、sex等都可以通過request.getParameter獲取到,當獲取二維數據"info"時卻打印爲null
        System.out.println(request.getParameter("info"));//null
        out.flush();
        out.close();
    }

原因

因爲前臺ajax的XMLHttpRequest對象send()方法(post方式)發送數據的數據格式應爲send(“name=key&age=18&sex=男”),卻不能是這樣的send(“…sex=男&info={…}”)即(不能爲info={…})。但是php卻能成功的接收到,而java卻爲null,這裏暫時將原因歸咎於java對數據的解析問題,如果有讀者知道根本原因還請評論留言給我,感激不盡。

解決方法

前臺代碼如下:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="jquery-1.7.2.js"></script>
    <script>
        $(document).ready(function(){
            $('#btn').click(function(){
                //將多維數據的值設爲json格式的字符串
                /*var obj={
                    name:'key',
                    age:18,
                    sex:'男',
                    info:"{qq:'123456',email:'[email protected]',girlFriend:{name:'lucy',age:18,sex:'女'}}"
                }*/
                //或者爲這樣(可以調用JSON.stringify(jsonObj)轉換爲字符串),整個用request.getParameter("data")接收
                var obj={data:"{name:'key',age:18,sex:'男',info:{qq:'123456',email:'[email protected]',girlFriend:{name:'lucy',age:18,sex:'女'}}}"}
                $.ajax({
                    type:'post',
                    url:'Test',
                    data:obj,
                    dataType:'json',
                    success:function(data){
                        console.log(data);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">按鈕</button>
</body>
</html>

後臺代碼如下:

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/plain;charset=utf-8");
        PrintWriter out = response.getWriter();
        System.out.println(request.getParameter("data"));
        JSONObject strJson = parseStr(request.getParameter("data"));
        try {
            System.out.println(strJson.getString("name"));//key
            System.out.println(strJson.getString("age"));//18
            System.out.println(strJson.getString("info"));
            //{"email":"[email protected]","girlFriend":{"sex":"女","age":18,"name":"lucy"},"qq":"123456"}
            out.write(strJson.getString("info"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        out.flush();
        out.close();
    }

    public JSONObject parseStr(String str) {
        try {
            return new JSONObject(str);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

其中用到的是:
java的json數據解析jar包[點擊下載]
jar包導入方法可根據自己的編輯器自行百度

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