submit form does not stop in jquery ajax call

前端 未结 6 1196
感动是毒
感动是毒 2020-11-29 12:29

I got following code :

$.ajax({
    type: \"POST\",
    async: false,              
    url: \"CheckIdExist\",
    data: param,
    success: function(result)         


        
6条回答
  •  既然无缘
    2020-11-29 12:56

    A slight variation of this question is: I want to use jquery and ajax to present an error message to a user, but then to do normal processing if there is no error.

    Suppose method "check" returns a response that is empty if there is no error, and has the error(s) in it if there are any.

    Then you can do something like this in your ready function:

    $("#theform").submit(function() {
        var data = { ... }
        $.get('/check', data,
            function(resp) {
                if (resp.length > 0) {
                    $("#error").html(resp);
                } else {
                    $("#theform").unbind('submit');
                    $("#theform").submit();
                }
        });
        event.preventDefault();
    });
    

    So, how does it work? When the outer submit function is triggered, it builds the data needed for the AJAX call (here the higher level function get). The call is scheduled, and the main thread of operation immediately continues, but the submit is unconditionally stopped, so nothing apparent happens.

    Some time passes, and the AJAX call returns the result of the request. If non-empty, the result is shown to the user.

    If the response is empty, however, the submit function is unbound. This prevents the ssytem from making an extra call through the outer submit function. The inner submit function is called. This triggers an actual form submission to the form's target, and life goes on as expected.

提交回复
热议问题