The processing method of returning the map collection in the background of AJAX request

Problem Description

Recently, I am re-learning servlet, which involves the format processing method of passing collection classes from the background to the front end. Only one example of map has been written so far. It uses alibaba's json parsing library.

Required shelf package or maven configuration

rack bag

fastjson-1.1.32.jar:

Download address: http://http://repo1.maven.org/maven2/com/alibaba/fastjson/

maven configuration

<properties>
    <fastjson_version>1.2.28</fastjson_version>
</properties>

<dependencies>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>${fastjson_version}</version>
    </dependency>
</dependencies>

The servlet sends the map collection to the front end

	Map<String, Object> map = new HashMap<>();
	map.put("residueAmount", residueAmount);//这是一个String
	map.put("paymentList", paymentList);//这是一个List<Map<String, Object>>

	//map集合转换为JSON对象
	JSONObject result = JSONObject.parseObject(JSON.toJSONString(map));
	//将JSON对象传递给前端AJAX接收
	resp.getWriter().print(result);

AJAX receive map collection

My JSP page source code:

get String

本月剩余¥:<span id="residueAmount"></span>

get datasheet

    <table class="table table-striped table-bordered bgcolorWhite">
        <thead>
            <tr>
              <th>#</th>
              <th>用途</th>
              <th>金额</th>
              <th>消费日期</th>
            </tr>
        </thead>
        <tbody id="paymentList"></tbody>
      </table>

My AJAX: source code

	$(document).ready(function() {
    	$.ajax({
    		url: "ListServlet",
    		method: "POST",
    		async: true,
    		success: function (data) {
    		//把JSON字符串转化为JSON对象
                var json = eval("("+data+")");

		//获取String
                $("#residueAmount").text(json.residueAmount);
                
                //获取List<Map<String, Object>>数据列表
                $("#paymentList").empty();
                var result = json.paymentList;
                if(result && result.length != 0) { //不为null,不为NaN,不为undefined
                	$.each(result, function(index, item) {
	                	var lineNumber = ++ index;
	                	var pay_amount = new Number(item.pay_amount).toFixed(2);
	                	var pay_usage = item.pay_usage;
	                	var pay_date = getDateTime(new Date(item.pay_date));
	                	var userid = item.userid;
	                	$("#paymentList").append("<tr><td>" + lineNumber + "</td><td>" + pay_usage + "</td><td>¥" + pay_amount + "</td><td>" + pay_date + "</td></tr>");
				    });
                }else{//当值为空时
                	$("#paymentList").append("<tr><td colspan='4'>暂无数据</td></tr>");
                }
            }
    	});
    });

Remark

The pay_date returned by the data list in my background is a datetime type. If the front end does not do any processing, it is a number with a length of 13 digits. Therefore, a conversion needs to be done. The converted JS processing source code is:

/* 获取日期格式 */
function getDate(date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    return year + "-" + month + "-" + day ; 
}

/* 获取日期时间格式*/
function getDateTime(date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hh = date.getHours();
    var mm = date.getMinutes();
    var ss = date.getSeconds();
    return year + "-" + month + "-" + day + " " + hh + ":" + mm + ":" + ss; 
}

It is recommended to put the JS of this tool class in a custom JS file instead of exposing it on the page. For example, add it to your local self-defined.js.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324982023&siteId=291194637