How to make JQuery-AJAX request synchronous

前端 未结 7 2022
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 09:55

How do i make an ajax request synchronous?

I have a form which needs to be submitted. But it needs to be submitted only when the user enters the correct password.

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 10:34

    Instead of adding onSubmit event, you can prevent the default action for submit button.

    So, in the following html:

    first, prevent submit button action. Then make the ajax call asynchronously, and submit the form when the password is correct.

    $('input[type=submit]').click(function(e) {
        e.preventDefault(); //prevent form submit when button is clicked
    
        var password = $.trim($('#employee_password').val());
    
         $.ajax({
            type: "POST",
            url: "checkpass.php",
            data: "password="+password,
            success: function(html) {
                var arr=$.parseJSON(html);
                var $form = $('form');
                if(arr == "Successful")
                {    
                    $form.submit(); //submit the form if the password is correct
                }
            }
        });
    });​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
    

提交回复
热议问题