1. 程式人生 > >JSP頁面呼叫介面傳送JSON格式資料

JSP頁面呼叫介面傳送JSON格式資料

問題描述:

1. 想在JSP頁面測試呼叫後臺介面,這個介面呼叫後需要進行頁面跳轉,所有無法使用Postman等工具

2. 介面接收的是JSON資料格式

在摸索了一番後,直接上可用程式碼片段:

<html>

<head>
    <title>支付測試</title>
</head>

<body>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script>
    function login() {
        var myData = {
            "account": "danisa",
            "password": "111111",
            "userType": 1
        };
        $.ajax({
            type: "POST",
            url: "http://127.0.0.1:8088/api/1.0/web/login",
            data: JSON.stringify(myData),
            contentType: "application/json;charset=UTF-8"
        });
    }
    </script>
    <h1>登入</h1>
    <input type="button" value="click me to login" onclick="login()">
</body>

</html>
其中需要注意的有兩個地方:

1. contentType,需要填成 application/json;charset=UTF-8,否則會報格式錯誤

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

2. data部分,要使用JSON.stringify()方法格式化json物件,否則會報以下錯誤

Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'account': was expecting ('true', 'false' or 'null')