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

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

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

zglosip(); (我想要被调用的function)

 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; }); }; 

validation脚本(由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 } } }); 

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

您希望首先确保没有提交表单,然后运行您的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(); } }); } }); 

在我的情况下,我不得不从按钮中删除提交类型,然后我不得不调用一个方法来检查我必须提交的数据的有效性。

  

然后我编写了一个执行检查的方法,如果我必须停下来并要求继续,则返回true:

  public ActionResult CheckBeforeSubbmission(datatype var1) { if(var1>0) return Json(new { result1 = true }); else return Json(new { result1 = false }); } 

之后我添加了以下代码的javascript / ajax:

  $("#submitbutton").click(function (e) { var self = $('#form'); //A value from the form to post to the controller var var1 = $('#var1elementid').val(); $.ajax({ type: "POST", url: "/SomeController/CheckBeforeSubbmission", data: { var1: var1 },success: function (response) { if (response.result1) { bootbox.confirm({ message: "The check failed! Do you want to submit?", buttons: { confirm: { label: 'Yes', className: 'btn-success' }, cancel: { label: 'Cancel', className: 'btn-danger' } }, callback: function (result) { if (result) { self.submit(); } else { bootbox.hideAll(); return false; } return false; } }); } else { self.submit(); } }, cache: false }); });