1 后端兩個輔助類
ConcurrentDateUtil.Java,用于生成我們需要格式的時間
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class ConcurrentDateUtil { private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" ); } }; public static Date parse(String dateStr) throws ParseException { return threadLocal.get().parse(dateStr); } public static String format(Date date) { return threadLocal.get().format(date); } } |
JsonResult.java,JsonResult封裝,用于后端向前端傳遞數據
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
import com.sf.utils.ConcurrentDateUtil; import java.util.Date; public class JsonResult<T> { public static int NEED_RE_LOGIN = 1 ; public static int NEED_RETRY = 2 ; private int errCode; private String message; private String timestamp = ConcurrentDateUtil.format( new Date()); private T data; public String getMessage() { return message; } public void setMessage(String message) { this .message = message; } public String getTimestamp() { return timestamp; } public T getData() { return data; } public void setData(T data) { this .data = data; } public int getErrCode() { return errCode; } public void setErrCode( int errCode) { this .errCode = errCode; } } |
上面這兩個類完成之后,我們就可以在web層的controller中使用JsonResult封裝數據并傳遞到前端。
接下來介紹兩種情況,看看前端怎么取數據出來
2 前端JS怎么取出數據
如果后端傳給前端的JsonResult封裝的是一個Map,例如
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
@ResponseBody @RequestMapping(value = "/user/getUserAmount" , method = RequestMethod.POST) public JsonResult<Map<String, Integer>> getUserAmount() { JsonResult<Map<String, Integer>> result = new JsonResult<>(); try { //已簽到人數 Integer signedAmount = userService.getSignedAmount(); //總人數 Integer totalUserAmount = userService.getTotalUserAmount(); Map<String, Integer> amountMap = new HashMap<>(); amountMap.put( "signed" , signedAmount); amountMap.put( "sum" , totalUserAmount); result.setData(amountMap); //這里舉個例子,如果覺得setData穿的信息不夠,還可以用setMessage方法多傳一個字符串過去 result.setMessage( "這是簽到界面" ); } catch (Exception e) { log.warn(ExceptionUtils.getStackTrace(e)); } return result; } |
現在想在前端JS把已簽到人數和總人數兩個數據取出來,要怎么做呢?只需要在”.”后面跟著Map的Key就好了,如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
function getSignedAmount(){ $.ajax({ type: "post" , url : getContextPath() + "/user/getUserAmount" , dataType: 'json' , data: { }, success: function (data){ var amount = data.data; //取出總人數 var totalAmount = amount.sum; //總人數減去已經簽到的人數,就是未簽到的人 var unsignedNumber = amount.sum-amount.signed; //取出后端controller中setMessage方法傳過來的字符串 var logMessage = data.message; } }); } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/antony9118/article/details/54411284