无法在表单POST中调用.js

Cannot get .js to be called upon form POST

本文关键字:调用 js POST 表单      更新时间:2023-09-26

我有一些代码在"工作",但没有做我想做的事情。

在我的页面上,我在标题中有一段代码:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="update.js"></script>

在我的主页中,我有:

<form id="updateChanges" method="POST" action="update.php">
...code...
</form>

当我单击此表单中的按钮时,我希望执行update.js中的代码,但页面重定向到update.php并成功执行我的代码。我试图绕过这个重定向,在不刷新页面的情况下执行代码。我不明白为什么它不起作用。

我从一个关于如何使用AJAX的教程中得到了.js。

$(function() {
    // Get the form.
    var form = $('#updateChanges');
    // Set up an event listener for the contact form.
    $(form).submit(function(event) {
    // Stop the browser from submitting the form.
    event.preventDefault();
    // Serialize the form data.
    var formData = $(form).serialize();
    // Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData
    })
});
});

我的javascript文件没有被调用。为什么?

您已经在form变量中定义了jQuery表单对象,不需要再次为jQuery包装它。

$(form)的所有实例变为:form

$(function() {
    // Get the form.
    var form = $('#updateChanges');
    // Set up an event listener for the contact form.
    form.submit(function(event) {
        // Stop the browser from submitting the form.
        event.preventDefault();
        // Serialize the form data.
        var formData = form.serialize();
        // Submit the form using AJAX.
        $.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: formData
        });
    });
});