DIV CSS 佈局教程網

Ajax + SpringMVC:Controller 與 View 之間的資料交換
編輯:AJAX基礎知識     

本篇以「留言/回覆」為例,示範如何用 jQuery 的 post/get 搭配 SpringMVC 的 @ResponseBody,完成前端與後端的資料交流。

先看 jQuery.post 的參數

jQuery.post(url, [data], [callback], [type])

  • url:請求位址。
  • data:待送出的 key/value 參數。
  • callback:送出成功後的回呼函式。
  • type:回傳內容格式,可為 xml、html、script、json、text。

基本用法

$.post("test.php", function (data) {
    alert("Data Loaded: " + data);
});

留言列表的取得與渲染

這裡後端回傳的是自訂分隔格式:每筆留言用 $ 分隔,欄位之間用逗號分隔,順序是「內容,時間,主鍵,姓名」。

$.get("comment/getComments?parentId=" + parentId + "&topicId=" + topicId, function (data) {
    var appendButton = "";
    var append = "";

    if (data != "") {
        var arr = data.split("$");
        var allTr = "";

        for (var i = 0; i < arr.length; i++) {
            var arr2 = arr[i].split(',');
            var name = arr2[3];
            var content = arr2[0];
            var time = "/Date(" + arr2[1] + ")/";
            time = DateFormat(time);
            var id = arr2[2];

            var table = "<table><tr><td>" + content + "</td></tr>"
                + "<tr><td>" + time + "</td></tr></table>";

            appendButton = appendButton + table
                + "<button type='button' id='toAddCommentId' onclick='replaceFrom("
                + parentId + ",\"" + name + "\")'>回復</button>";
        }

        appendButton = appendButton
            + "<button type='button' onclick='replaceFrom(" + parentId + ",\"" + userName + "\")'>我也說一句</button>";
    }

    appendButton = appendButton
        + "<div id='commentButton'></div><div id='textareaId'></div>";

    if (data == "") {
        appendButton = appendButton
            + "<textarea id='textareaId" + parentId + "' rows='2' cols='77'"
            + " validate='required' validate-message='不能為空!' name='content'>@"
            + userName + "...." + parentId + ":</textarea>"
            + "<button type='button' id='commentContentId' onclick='submit("
            + topicId + "," + parentId + ",\"" + userName + "\")'>發表</button>";
    }

    $("#addCommentId" + parentId).html(appendButton);
});

後端 Controller

@RequestMapping(value = "/saveAndGetComments",
    params = { "topicId", "parentId" }, method = RequestMethod.POST)
@ResponseBody
public String saveAndGetComments(long topicId, Comment comment, long parentId)
        throws UnsupportedEncodingException {
    comment.setParentId(parentId);
    commentService.save(comment, topicId);
    List<Comment> comments = commentService.listByCommentId(parentId);
    return append(comments);
}

private String append(List<Comment> comments) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < comments.size(); i++) {
        Comment comment = comments.get(i);
        sb.append(comment.getContent());
        sb.append(",");
        sb.append(comment.getCreateTime().getTime());
        sb.append(",");
        sb.append(comment.getId());
        sb.append(",");
        sb.append(comment.getUser().getName());
        if (i != comments.size() - 1) {
            sb.append("$");
        }
    }
    return sb.toString();
}

重點:靠 SpringMVC 的 @ResponseBody 把回傳物件直接寫入回應本文,而不是去找檢視。

順手處理日期格式

後端傳過來的時間是 Date.getTime() 的毫秒數,前端拿到的會是 /Date(1483200000000)/ 這種 .NET 風格的字串,需要自己轉:

var date = "/Date(" + time + ")/";
date = DateFormat(date);

/**
 * 處理時間
 * @param value 形如 /Date(1483200000000)/ 的字串
 * @returns {String} yyyy/MM/dd HH:mm:ss
 */
function DateFormat(value) {
    var date = new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));

    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var Hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var Minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var Seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

    return date.getFullYear() + "/" + month + "/" + currentDate
        + " " + Hours + ":" + Minutes + ":" + Seconds;
}

實務上建議直接用 JSON 搭配 Jackson 序列化日期物件,並在欄位上標註 @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss"),就不需要在前端做這些字串手術了。

以上就是 Ajax + SpringMVC 完成 Controller 與 View 資料交流的做法,希望能給大家一個參考。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved