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

前端 未结 3 1835
陌清茗
陌清茗 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);
    })
    

提交回复
热议问题