为了账号安全,请及时绑定邮箱和手机立即绑定

我的 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 关注
  • 33 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信