亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我的 Servlet 端點返回 JSON,但我的 AXIOS 函數未運行并為我的網頁獲取它

我的 Servlet 端點返回 JSON,但我的 AXIOS 函數未運行并為我的網頁獲取它

胡說叔叔 2024-01-18 14:44:57
我有一個簡單的 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") 甚至沒有運行?這可能很簡單,但我堅持下去。
查看完整描述

1 回答

?
慕容708150

TA貢獻1831條經驗 獲得超4個贊

您的腳本標簽指定了“src”以及內聯javascript,當您像這樣編寫時,您的內聯js將被忽略,因此您必須分隔這些腳本標簽:


<script src='path/to/axios/'></script>

<script>

// register your form handler

</script>

還有這一行:


form.addEventListener('submit', servletAccess())

您將實際的函數調用注冊為事件偵聽器,而不應該是函數本身,如下所示:


// notice no () at the end of function name

form.addEventListener('submit', servletAccess)


查看完整回答
反對 回復 2024-01-18
  • 1 回答
  • 0 關注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號