为什么当点击输入类型submit时,on('submit')函数从不被调用?

Why is on('submit') function is never called when clicking on input type submit?

本文关键字:submit 函数 调用 输入 类型 on 为什么      更新时间:2023-09-26

昨天一切都很好,但今天我做了一个愚蠢的事情,onsubmit jquery回调崩溃了。

首先,jQuery是在类路径和其他回调工作。但我不能注册回调提交事件与jQuery。我的回调:

var $form = $('#hostelSearchForm');
    $form.on('submit', function(e) {
            //console.log($('#hostelSearchFormButton').attr('id'));
            hostelSearchJson = collectHostelSearchFormData($form);
            console.log(JSON.stringify(hostelSearchJson));
            //do ajax search
            hostelSearch(hostelSearchJson);
            //serializing is bad because of checkboxes value as on and off
            // console.log(JSON.stringify($form.serialize()));
            e.preventDefault();
            return false;
        });

这个表单对应的输入类型是submit:

<form:form id="hostelSearchForm" modelAttribute="hs" method="POST"
                cssClass="mainForm">
.........................
<div>
                    <fmt:message key="searchButtonLabel" var="searchButtonLabel" />
                    <input id="hostelSearchFormButton" type="submit" class="btn btn-primary"
                            style="font: bold 18px Tahoma, serif; padding: 15px"
                            value="${searchButtonLabel}" />
                            &nbsp;&nbsp;&nbsp;&nbsp;
                        <button type="reset" class="btn">
                            <fmt:message key="cancel" />
                        </button>
                </div>
</form:form>

当我点击hostelSearchFormButton时,它将我重定向到新页面并给出

415 Unsupported Media Type. 

在chrome中,我看到它使post请求与text/html作为媒体类型。

即使我在hostelSearchFormButton上附加回调,它也不会被触发。但是本页上所有其他回调都运行良好。

这是如此愚蠢的错误,我不明白是怎么回事?

问得好,

这会发生,因为提交在第一个实例中使用HTML在javascript之后,所以当你点击它,默认HTML发送表单数据,以避免这种影响添加在你的表单标签onsubmit="return false"像这样:

<form action="my.php" onsubmit="return false">
当你在jquery中完成你想做的事情时,你可以用 发送数据
$('form').submit();

再会