Can I preventDefault(); inside of an ajax callback?

前端 未结 3 1798
陌清茗
陌清茗 2021-01-11 13:58

I\'m doing some form validation, and I\'m having trouble with what I\'m trying to accomplish. I want to be able to validate my zip code on blur of the field, but also call t

相关标签:
3条回答
  • 2021-01-11 14:11

    You need to prevent the event's default action before it's bubbled up and handled by the browser. $.getJson returns control and allows the validateZipCode function to finish first, so you need to do this:

    function validateZipCode(event){
        event.preventDefault(); //stop the form from being submitted
        $.getJson(
            url,
            params,
            function(data){
                if(data.response === false){
                    someError.show();
                }
            }
        );
    }
    
    $('#someForm').submit(function(event){
        validateZipCode(event);
    });
    
    $('#zipInput').blur(function(event){
        validateZipCode(event);
    })
    
    0 讨论(0)
  • 2021-01-11 14:16

    No, without using the ajax() method and setting async to false, you can't return anything from your ajax request.

    A better idea would be to always prefent default on your submit, and then manually submit the form in the ajax callback.

    0 讨论(0)
  • 2021-01-11 14:17

    No, by the time the callback from the AJAX event fires, the event will have already bubbled and the form submitted. One way you could accomplish this is cancel the form from submitting and then submit it manually if it passes the requirements from the AJAX request.

    0 讨论(0)
提交回复
热议问题