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?
更新:我最初将它绑定到按钮单击事件并且它正在工作但我想保留提交按钮的[enter]键元素。看到代码有点不合逻辑,抓住按键会更好吗?
3 个解决方案
#1
42
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.
我假设您的ajax是在最终提交之前验证表单的尝试。在这种情况下,只需在提交表单之前取消绑定验证功能。
success: function(response){
$('input[name="field1"]').val(response);
// Add unbind to remove validations
$('form').unbind().submit();
}
#2
6
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
3
You submit your form, prevent submission only to submit the form, which gets prevented to get submitted... :-D
您提交表单,阻止提交仅提交表单,以防止提交... :-D
#1
42
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.
我假设您的ajax是在最终提交之前验证表单的尝试。在这种情况下,只需在提交表单之前取消绑定验证功能。
success: function(response){
$('input[name="field1"]').val(response);
// Add unbind to remove validations
$('form').unbind().submit();
}
#2
6
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
3
You submit your form, prevent submission only to submit the form, which gets prevented to get submitted... :-D
您提交表单,阻止提交仅提交表单,以防止提交... :-D