胡說叔叔
2024-01-18 14:44:57
我有一個(gè)簡(jiǎn)單的 HTML 表單<form action="#" method="get" id="thisForm"> <button type="submit"> GetJSON </button></form>這是我的 body 標(biāo)簽?zāi)┪膊糠值?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());當(dāng)通過 URL 直接訪問我的端點(diǎn)時(shí),我得到原始數(shù)據(jù)[{"lname":"所羅門","name":"rene","age":28},{}]所以我知道我的端點(diǎn)有效。為什么我什至無法 console.log 響應(yīng)?我的虛擬 console.log("im here") 甚至沒有運(yùn)行?這可能很簡(jiǎn)單,但我堅(jiān)持下去。
1 回答

慕容708150
TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超4個(gè)贊
您的腳本標(biāo)簽指定了“src”以及內(nèi)聯(lián)javascript,當(dāng)您像這樣編寫時(shí),您的內(nèi)聯(lián)js將被忽略,因此您必須分隔這些腳本標(biāo)簽:
<script src='path/to/axios/'></script>
<script>
// register your form handler
</script>
還有這一行:
form.addEventListener('submit', servletAccess())
您將實(shí)際的函數(shù)調(diào)用注冊(cè)為事件偵聽器,而不應(yīng)該是函數(shù)本身,如下所示:
// notice no () at the end of function name
form.addEventListener('submit', servletAccess)
添加回答
舉報(bào)
0/150
提交
取消