SpringBoot 後端接 json 範例


Posted by c9103205 on 2021-07-16

雖然這個很基本
但是如果沒有範例的話
憑空寫出來還蠻困擾的,尤其是前後端對測的時候
有時候接不到值問題百百種,結果原來只是打錯字而已

在此貼上範例,如果您在找範例,此寫法親測可用
前端代碼:

                    let  queryTextVal = $("#queryText").val();  //取input值
                    var jsonData={"queryText":queryTextVal}; 
                    $.ajax({
                        url: '/adgP003/query',
                        contentType: "application/json",
                        method: 'post', 
                        data: JSON.stringify(jsonData), 
                        dataType :'json',
                        beforeSend:function(){

                        },
                        success: function (res) {
                            console.log(res.resultList);
                        },
                        error: function (err) {
                            console.log(err.responseText);
                        },
                    });

後端controller,關鍵字 @RequestBody

@PostMapping("adgP003/query")
public AjaxReport adgP003(@RequestBody FormObject formObject)

使用物件接參數,注意參數的名字要跟前端傳過來的一樣

public class FormObject {
    String queryText ;
    public String getQueryText() {
        return queryText;
    }
    public void setQueryText(String queryText) {
        this.queryText = queryText;
    }
}

#ajax #Sping #SpringBoot







Related Posts

AWS 遠端主機部署與連線

AWS 遠端主機部署與連線

W14_伺服器與網站部署

W14_伺服器與網站部署

React 基礎

React 基礎


Comments