我有一個簡單的 HTML 表單<form action="#" method="get" id="thisForm"> <button type="submit"> GetJSON </button></form>這是我的 body 標簽末尾部分的 javascript<script src="https://unpkg.com/axios/dist/axios.min.js">let form = document.getElementById("thisForm");form.addEventListener('submit', servletAccess())function servletAccess(e){ e.preventDefault(); console.log("im here") axios.get('http://localhost:8080/Project1/MyServlet') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .then(function () { console.log(response); });} </script>這是我的 java servlet 返回 JSON JSONArray json = new JSONArray(); JSONObject user = new JSONObject(); user.put("name", "rous"); user.put("age", 26); user.put("lname", "e"); JSONObject user2 = new JSONObject(); user.put("name", "rene"); user.put("age", 28); user.put("lname", "solomon"); json.put(user); json.put(user2); response.setContentType("application/json"); response.getWriter().write(json.toString());當通過 URL 直接訪問我的端點時,我得到原始數據[{"lname":"所羅門","name":"rene","age":28},{}]所以我知道我的端點有效。為什么我什至無法 console.log 響應?我的虛擬 console.log("im here") 甚至沒有運行?這可能很簡單,但我堅持下去。
我的 Servlet 端點返回 JSON,但我的 AXIOS 函數未運行并為我的網頁獲取它
胡說叔叔
2024-01-18 14:44:57