Jquery form check returns true, but need to return false

前端 未结 2 1984
眼角桃花
眼角桃花 2020-12-20 01:34

I am running this form check when the form is submitted:

if((formData[4].value == 1 || formData[4].value == 2) && !formData[2].value) { 
    alert(\'         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-20 02:00

    The problem is that the AJAX request happens asynchronously — it calls your success function after the outer function returns true. It is the success function (not your outer function) returning false, which has no bearing on whether the form will submit or not.

    You will have to always return false from that outer function, and then in the AJAX success function, if the validation succeeds, unbind the initial submit handler and use the .submit() method of the form to submit the form normally:

    (In these code samples, I assume that form is a jQuery object that wraps the underlying DOM element of the form.)

    success: function(data) {
        if(data == 1) {
            alert('Key already exists');
        } else {
            form.unbind('submit'); // Prevent the AJAX validation from happening again
            form.submit(); // Submit the form normally
        }
    }
    

    Alternatively, you can call the browser's native form.submit() method and the "unbind" line will not be necessary:

    form[0].submit();
    

提交回复
热议问题