How to make JQuery-AJAX request synchronous

前端 未结 7 2024
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 10:32

    try this

    the solution is, work with callbacks like this

    $(function() {
    
        var jForm = $('form[name=form]');
        var jPWField = $('#employee_password');
    
        function getCheckedState() {
            return jForm.data('checked_state');
        };
    
        function setChecked(s) {
            jForm.data('checked_state', s);
        };
    
    
        jPWField.change(function() {
            //reset checked thing
            setChecked(null);
        }).trigger('change');
    
        jForm.submit(function(){
            switch(getCheckedState()) {
                case 'valid':
                    return true;
                case 'invalid':
                    //invalid, don submit
                    return false;
                default:
                    //make your check
                    var password = $.trim(jPWField.val());
    
                    $.ajax({
                        type: "POST",
                        async: "false",
                        url: "checkpass.php",
                        data: {
                            "password": $.trim(jPWField.val);
                        }
                        success: function(html) {
                            var arr=$.parseJSON(html);
                            setChecked(arr == "Successful" ? 'valid': 'invalid');
                            //submit again
                            jForm.submit();
                        }
                        });
                    return false;
            }
    
        });
     });
    

提交回复
热议问题