Infinite loop of form submit using jquery event

泄露秘密 提交于 2019-11-27 17:37:30

问题


The code is stuck in a loop when I try to catch a form submission. The purpose is to replace a value of the form before it goes out.

$('form').submit(function(e){
   e.preventDefault();
   $.ajax({
      type: "POST",
      url: 'convert.asp',
      data: $('form').serialize(),
      success: function(response){
         $('input[name="field1"]').val(response);
         $('form').submit();
      }
   });
   return false;
});

Does anyone have any ideas?

UPDATE: I originally had it bound to a button click event and it was working but I wanted to preserve the [enter] key element of the submit button. Seeing that the code is kind of illogical, would catching a keypress be a better idea?


回答1:


I assume your ajax is an attempt to validate the form before its eventual submission. In that case just unbind the validation function before submitting the form.

  success: function(response){
     $('input[name="field1"]').val(response);
     // Add unbind to remove validations
     $('form').unbind().submit(); 
  }



回答2:


In the success you trigger another submit...

$('form').submit(function(e){
   e.preventDefault(); // redundant,  you return false in the end. <<<===
   $.ajax({
      type: "POST",
      url: 'convert.asp',
      data: $('form').serialize(),
      success: function(response){
         $('input[name="field1"]').val(response);
         $('form').submit(); // <=== delete this! <<<<=================
      }
   });
   return false;
});



回答3:


You submit your form, prevent submission only to submit the form, which gets prevented to get submitted... :-D



来源:https://stackoverflow.com/questions/9812876/infinite-loop-of-form-submit-using-jquery-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!