Resume form submission after $.ajax call

2019-09-14 22:13发布

问题:

How can I resume/stop form submission after jQuery ajax call? I have MVC application, I'm calling an action by json, I want to stop form submission if result came false and to resume if result came true.

Jquery:

   $("#formElem").submit(function (e) {
        e.preventDefault();
        $.ajax({
            url: '@Url.Action("Check", "TimeRanges")',
            type: "GET",
            data: {startRange: $('#SelectedStartTimeRange').val() , endRange: $('#SelectedEndTimeRange').val()},
            aync: false,
            dataType: 'json',
            success: function (data) {
                if(data == false) {
                    $("#rangeexist").html('Error');
                    return false;
                } else {
                    return true;
                }
            }
        });
    });

Action

public JsonResult Check(string startRange, string endRange)
{
    var result = false;
    if (!String.IsNullOrEmpty(startRange) && !String.IsNullOrEmpty(endRange))
    {
        TimeSpan spanStart;
        TimeSpan.TryParse(startRange, out spanStart);

        TimeSpan spanEnd;
        TimeSpan.TryParse(endRange, out spanEnd);

        var timeRangExisted = _repo.All().Where(x => x.TimeFrom.Equals(spanStart) && x.TimeTo.Equals(spanEnd)).ToList();
        if (!timeRangExisted.Any())
            result = true;
    }

    return Json(result, JsonRequestBehavior.AllowGet);
}

回答1:

var ajaxSent = false;
$("#formElem").submit(function (e) {
    if ( !ajaxSent )
     e.preventDefault();
    $.ajax({
        url: '@Url.Action("Check", "TimeRanges")',
        type: "GET",
        data: {startRange: $('#SelectedStartTimeRange').val() , endRange: $('#SelectedEndTimeRange').val()},
        aync: false,
        dataType: 'json',
        success: function (data) {
            if(data == false) {
                $("#rangeexist").html('Error');
                ajaxSent = true;
                $("#formElem").submit(); // something like that ....
                return false;
            } else {
                return true;
            }
        }
    });
});