JS:提交表单并在同一页面上呈现结果

问题描述

提前为我的天真道歉,我绝对不是网络开发人员。

我正在尝试获取一个简单 HTML 表单的内容,将其作为 GET 请求提交给我正在运行的一个非常轻量级的服务器,并在同一页面上呈现结果。到目前为止,这是我的代码

<head>
    <Meta charset="UTF-8">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <script>
        var submit_button = $('#submit_form');
        
        submit_button.click(function() {
            
            var word = $('word').val();
            
            var data = '?word=' + word;
            
            var update_div = $('#update_div');
            
            $.ajax({
                type: 'GET',url: 'http://35.45.55.65:5000/api',data: data,success:function(html){
                    update_div.html(html);
                console.log("Done");
                console.log(html)
                }
            });
        });
    </script>
    <h1>Enter a word to check</h1>
    <form id="my_form">
        Word: <br/> <input name="word" id="word" type="text" /><br />
        <input id="submit_form" type="submit" value="Submit">
    </form>
    
    <div id="update_div"></div>

从我读过的所有内容来看,这段代码应该有效吗?然而,表单根本没有被提交,相反,GET 请求被附加到当前 URL 甚至没有运行 JS 代码——就像这样:currentURL.com/test.html?word=hello+world

我真的不确定这里发生了什么,任何帮助将不胜感激!!谢谢:)

解决方法

您需要阻止表单的默认行为。这就是您将这些值附加到 URL 的原因。

submit_button.click(function (event) {
  event.preventDefault();
 // rest of code
}