Ajax calls Struts2 to call back JSON data and parse it

Posted by easethan on Fri, 12 Jul 2019 21:56:05 +0200

It's early in the morning - - on the way to learning Java, the farther and farther away.
Struts 2 with Ajax today encountered a small problem, so record it, I hope it can also help your friends.~

1. Writing of Action in Struts 2

package com.clay.action;

import org.json.JSONArray;
import org.json.JSONObject;

public class LolAction extends ActionSupport {
    String jsonData;

    public String find() throws Exception {
        List<Lol> list = lolService.findAllLol();

        // Array, a single array containing a Lol object
        JSONArray array = new JSONArray();
        for (Lol lol : list) {
            JSONObject obj = new JSONObject();
            obj.put("id", lol.getId());
            obj.put("name", lol.getName());
            obj.put("sex", lol.getSex());
            array.put(obj);
        }

        //Returning to the front desk will automatically wrap JSONObject
        jsonData = array.toString();

        return SUCCESS;
    }

    public String getJsonData() {
        return jsonData;
    }

    public void setJsonData(String jsonData) {
        this.jsonData = jsonData;
    }
}

It should be noted that:

  1. The parameters returned must provide a getter method.
  2. When splicing JSON, no external is needed, For example:
    JSON:[{"hello": "world"}]
    JSON:{"jsonData": [{"hello":"world"}} retrieved from the front desk
  3. In action, return, SUCCESS will do without specifying parameters.

2. Struts configuration file

<package name="lol" extends="json-default" namespace="/">
        <action name="findAllLol" class="LolAction" method="find">
            <result type="json">
                <param name="json">jsonData</param>
            </result>
        </action>
</package>

It should be noted that:

  1. package inherits from json-default
  2. The type in result is json

3.jsp page code

<script type="text/javascript" src="js/jquery-3.2.0.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#sendAjax").click(function() {
            ajsx();
        });
    });
    function ajsx() {
        $.ajax({
            type : "POST", //Mode of submission
            url : "findAllLol", //Address submission
            data : "", //Submitting parameters
            dataType : "json", //Return parameter type
            success : function(msg) {
                $("#info").html(""); //Clear up info content
                /**
                    String is returned. It seems useless to modify the return parameter type here. It's not clear.
                    You need to convert $. parseJSON to JSON format to each
                    One thing to note is that data.jsonData(jsonData) here is the parameter name passed from Strust.
                */
                $.each($.parseJSON(msg.jsonData), function(i, item) {
                    $("#info").append(
                        "<div>" + item.sex + "</div>" +
                        "<div>" + item.name + "</div>" +
                        "<div>" + item.id + "</div><hr/>");
                })
            }
        });
    }
</script>
</head>

<body>
    <input type="button" id="sendAjax" value="Ajax request" />
    <div id="info"></div>
</body>
</html>

Notes are written on everything that needs attention.

Finally, attach the running effect map.
1. Unparsed JSON (we can see that the header automatically adds the corresponding parameter name) ignores\ This is just an escape character.

2. Effect after parsing

Finally, the main purpose of Struts is to configure files and create getter methods.
There are many ways to parse JSON, and I'm just using the tip of the iceberg here.
Personally, it feels better to use the $ajax method

The following is more concise and free to choose

$.getJSON("request url", function(data//The parameters returned) {
    $("#info").html(""); //Clear up info content
    $.each(data.Parameter name, function(i, item) {
        $("#info").append(
            "<div>" + item.Subparameter + "</div><hr/>");
    });
});

Let's tell you about the errors that can easily occur when parsing JSON (JavaScript):
1,Cannot use 'in' operator to search for 'length' in

(We've got the data in this step.) This mistake means that the return is a String type, and the sub-attributes can't be iterated over. Just convert it into JSON format, as follows:

$.parseJSON(JSON)

2,Uncaught SyntaxError: Unexpected token u in JSON at position 0
If the data is not shown here, the error will be reported, which means that it was not retrieved at all. The type of retrieved data needs to be changed to JSON.

dataType : "json"

A lot of nonsense has been said. Thank you for your patience. I hope you can understand it.
Anything else you want to ask me, you can ask me, I'm not very skilled, but I can help you as much as I can.

QQ.2095204800

Topics: JSON Struts Javascript Java