JQuery AJAX的Click事件未执行

我正在尝试建立一个网站,可以通过该网站更新页面上的文本字段。在网站的“管理员”页面上,我允许用户在按下按钮时通过运行AJAX请求来设置字段。但是,按下按钮后没有任何反应。

我正在使用Express.js + E.js + JQuery。

admin.ejs

<!DOCTYPE html>

<html>

<head>
    <link rel="stylesheet" type="text/css" href="css/admin.css">
    <title>Manage the website</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

    <script>
        $(document).ready(function(){
            $("#submitButton").click(function(){
                $.ajax({
                    url: 'updateData',
                    type: 'POST',
                    data: {
                        text: 'email@example.com',
                        message: 'hello world!'
                    },
                });
            });
        });
    </script>
</head>


<header>
    <!-- Put partial includes here -->
</header>

<div class="topPage">


  <h1>Hello, <%= firstName %>!</h1>
<p1>
    Find a value you would like to edit, then press send. The website can take up to 10 mins for the changes to apply. The changes will not change live.
</p1>
</div>

<div class="homepage">
    <div class="information">
        <h1>
            Homepage variables
        </h1>
        <p1>
            Variables for the 'homepage' page are displayed below. Changes can take up to 10 mins to apply globally.
        </p1>
        <hr>
    </div>
    <div class="form">
        <label>
            Change the 'body' of 'homepage'
        </label>

        <form action="javascript:void(0)">
            <input type="text" id="textField" name="text" value="<%= pageData.get('homepage').homeBody%>" required>
            <input type="submit" id="submitButton">
        </form>

    </div>

</div>

<script>

</script>


</html>


我将表单的操作设置为void以确保不会重新加载页面,但是我仍然需要Ajax才能工作。

In the website.js file (where the express app is) I console.log() the request body to make sure it is coming through. Nothing is logging.

website.js

app.post('/updateData', async (req, res) => {
    console.log(req.body)
})

当按下表单提交按钮时,ajax应该运行。

我是Web开发的新手,因此非常感谢所有帮助!

谢谢!

评论
  • uanimi
    uanimi 回复

    id =“ submit Button”应该是按钮,而不是输入。更改输入的id标记,并在该Form中添加一个按钮,并将“ submitButton”作为ID

    希望能帮助到你