正在提交常规表单之前的AJAX请求

Grz*_* G. 10 forms ajax jquery

我有一个jQuery表单验证脚本,在用户尝试提交时执行.我希望在表单验证之后但在发送之前执行(并完成)AJaX请求的另一个函数.

这是脚本.单独调用时,zglosip函数可以正常工作; 即不是来自submit()功能内部.

zglosip(); (我想要被调用的功能)

function zglosip() {
        $.ajax({
            type : 'post',
            url : 'res/php/nZglos.php',
            data : {
            "erepid" : "111",
            "ip" : "222",
            "poz" : "333"
            },
            success : function(data, textStatus, jqXHR) {
            tempor.html(data);
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
            tempor.html(errorThrown);
            },
            dataType : 'text'
            return true;
        });
    };
Run Code Online (Sandbox Code Playgroud)

验证脚本(由Joren Rapini创建并由我修改)

pole&tempor是包含某些div名称的变量

$("#forml").submit(function(){  
    //Validate required fields
    if ((pole.val() == "") || (pole.val() == blad)) {
        pole.addClass("podkresl");
        pole.val(blad);
    } else {
        pole.removeClass("podkresl");
    }
    // Validate the e-mail.
    if (!/\b(https?|ftp|file):\/\/[\-A-Za-z0-9+&@#\/%?=~_|!:,.;]*[\-A-Za-z0-9+&@#\/%=~_|]/.test(pole.val())) {
        pole.addClass("podkresl");
        pole.val(blad);
    }


    if ($(":input").hasClass("podkresl")) {
        return false;
    } else {
      if (zglosip() == true) {
          return true
      }
    }
});
Run Code Online (Sandbox Code Playgroud)

正如您已经发现的那样,我试图在返回true submit()之后zglosIp()返回true 函数(脚本底部的if语句).不幸的是,这不起作用,我也试过zglosip()单独调用,function{return true}但我肯定没有正确使用它.请帮我.

小智 24

您希望首先确保没有提交表单,然后运行您的ajax调用,如果调用成功,请继续提交.注意我从zgoslip中删除了ajax调用并将其放在表单的提交处理程序中.你可以按照你想要的方式重组它:

$('form').submit(function(e) { 

     // this code prevents form from actually being submitted
     e.preventDefault();
     e.returnValue = false;

     // some validation code here: if valid, add podkres1 class

     if ($('input.podkres1').length > 0) { 
        // do nothing
     } else {

        var $form = $(this);

        // this is the important part. you want to submit
        // the form but only after the ajax call is completed
         $.ajax({ 
             type: 'post',
             url: someUrl, 
             context: $form, // context will be "this" in your handlers
             success: function() { // your success handler
             },
             error: function() { // your error handler
             },
             complete: function() { 
                // make sure that you are no longer handling the submit event; clear handler
                this.off('submit');
                // actually submit the form
                this.submit();
             }
         });
     }
});
Run Code Online (Sandbox Code Playgroud)