我的 Servlet 端点 returns JSON 但我的 AXIOS 函数没有 运行 并为我的网页获取它

My Servlet Endpoint returns JSON but my AXIOS function doesnt run and fetch it for my webpage

我有一个简单的HTML表格

<form action="#" method="get" id="thisForm">
       <button type="submit"> GetJSON </button>
</form>

这是我的 java正文标签末尾的脚本

<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 直接转到我的端点时,我得到了 RAW 数据

[{"lname":"solomon","name":"rene","age":28},{}]

所以我知道我的端点有效。

我怎么连console.log回复都没有? 我的假人 console.log("我在这里") 甚至 运行?

这可能很简单,但我坚持了下来。

你的脚本标签指定了'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)