有一个标题为 NEWFORM 的按钮。它用于在单击时创建新表单。每个表单有两个按钮。这两个按钮用作提交,并且有两个不同的操作请求页面。我的代码运行良好。我正在通过 ajax 方法发送我的表单数据,但我不喜欢这样。我想更改我的代码而不发送 ajax 方法。有办法做到这一点吗? 这是我的片段:
$(document).ready(function() {
$(".newform").click(function() {
$(".MyForm")
.eq(0)
.clone()
.show()
.insertAfter(".MyForm:last");
});
//click handler for add from DB
$('body').on('click', '.addfromdb', function(e) {
e.preventDefault() // To make sure the form is not submitted
var $frm = $(this).closest('.MyForm');
console.log($frm.serialize());
$.ajax(
$(this).attr('formaction'),
{
method: $frm.attr('method'),
data: $frm.serialize()
}
);
});
//click handler for remove from DB
$('body').on('click', '.removefromdb', function(e) {
e.preventDefault() // To make sure the form is not submitted
var $frm = $(this).closest('.MyForm');
console.log($frm.serialize());
$.ajax(
$(this).attr('formaction'),
{
method: $frm.attr('method'),
data: $frm.serialize()
}
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span class="newform">NEWFORM+</span>
<div class="all">
<form class="MyForm" method="post">
<input type="text" placeholder="name" value="Aynaz" name="a1" />
<select name="Avg">
<option value="1">1</option>
<option value="2">2</option>
</select>
<button type="submit" formaction="first.htm"class="addfromdb">add</button>
<button type="submit" formaction="secondpage.htm" class="removefromdb">Remove</button>
</form>
</div>
最佳答案
如果您想动态设置表单action
而不执行ajax,请尝试更改为:
$('body').on('click', '.removefromdb, .addfromdb', function(e) {
var $frm = $(this).closest('.MyForm');
$frm.attr('action', $(this).attr('formaction'));
});
这将更新操作,然后表单将通过浏览器默认流程提交
关于javascript - 如何不用ajax方法单独提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41341411/