0

单击提交按钮时,我试图捕捉提交并执行快速 AJAX 请求,以查看表单中指定的时间和日期的预订是否已经存在。如果是这样,请停止提交表单并提醒用户日期和时间的预订已经存在!如果没有预订,请继续提交表格。对于我的生活,我无法.preventDefault让它工作,除非我把它放在提交功能的末尾。非常感谢任何想法和指示,我已经坚持了三个小时,而且似乎并没有快速取得任何进展。我 99% 确定我只是个白痴,所以提前道歉!

这是我的代码:

$('#formID').submit(function(event){

            var InspectionDate = $('#datepicker').val().split('/');
            InspectionDate.reverse();
            InspectionDate = InspectionDate.join('-');
            InspectionHour = $('#time_hour').val();
            InspectionMinutes = $('#time_minutes').val();
            var InspectionDateTime = InspectionDate + ' ' + InspectionHour + ':' + InspectionMinutes + ':00';
            $.ajax({
               type: "POST",
               url: "ajax_booking_check.php",
               data: 'InspectionDateTime='+ InspectionDateTime,
               cache: false,
               success: function(response){
                if(response = 1){
                alert("An appointment for the selected Date and Time already exists.\n\nDouble Bookings are not possible.\n\nPlease refer to the calender to find an available appointment.");
                event.preventDefault();
                }
                else{
                //submit form   
                }
               }
            });
        });
4

2 回答 2

2

您需要将 放在event.preventDefault方法的开头,而不是成功回调

$('#formID').submit(function(event){
    event.preventDefault();
    var InspectionDate = $('#datepicker').val().split('/');
    ...
});
于 2013-04-03T20:55:18.140 回答
0

将 preventDefault 作为第一行,然后如果要提交表单,请在表单元素上调用 submit 方法。通过调用表单元素的提交方法而不是 jQuery 定义的方法,它将绕过 jQuery 绑定的提交事件处理程序。

$('#formID').submit(function (event) {
    event.preventDefault();
    var form = this;
    var InspectionDate = $('#datepicker').val().split('/');
    InspectionDate.reverse();
    InspectionDate = InspectionDate.join('-');
    InspectionHour = $('#time_hour').val();
    InspectionMinutes = $('#time_minutes').val();
    var InspectionDateTime = InspectionDate + ' ' + InspectionHour + ':' + InspectionMinutes + ':00';
    $.ajax({
        type: "POST",
        url: "ajax_booking_check.php",
        data: 'InspectionDateTime=' + InspectionDateTime,
        cache: false,
        success: function (response) {
            if (response = 1) {
                alert("An appointment for the selected Date and Time already exists.\n\nDouble Bookings are not possible.\n\nPlease refer to the calender to find an available appointment.");
            } else {
                form.submit();
            }
        }
    });
});
于 2013-04-03T20:56:03.017 回答