如何在具有Ajax的单个表单中使用多个Submit按钮 [英] How to use multiple Submit buttons in a single form having Ajax
问题描述
我正在构建一个使用mysql作为后端的简单网站.我有一个具有2个按钮的表单,其中一个按钮从db搜索数据并使用Ajax填充页面,另一个按钮将新值更新为db.现在我的问题是我不能同时使用两个按钮作为提交"按钮.
I'm building a simple website which uses mysql as backend. I have a form which has 2 buttons of which one searches data from db and populates the page using Ajax another button updates the new values to db. Now my problem is i can't use both buttons as 'Submit' button.
Ajax方法& HTML格式:
Ajax Method & Html Form:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '#update-form', function(){
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'search.php',
data : data,
success : function(data){
$(".display").html(data);
}
});
return false;
});
});
</script>
<body>
<div id="update" class="tab-pane fade">
<form id="update-form" role="form" class="container" method="post" action="search.php">
<h3>Update details</h3>
<table class="display">
<tr class="space">
<td><label>File Number:</label></td>
<td><input type="text" class="form-control" name="filenum" required></td>
</tr>
</table>
<button type="submit" class="btn btn-default text-center" name="search_btn" >Search</button>
<button type="submit" class="btn btn-default text-center" name="submit_btn" formaction="update.php">Update</button>
</form>
</div>
</body>
现在我想知道如何修改上面的代码,以便我可以将两个按钮都用作提交.
Now i want to know how can i modify above code so that i can use both button as submit.
尝试过 formaction
,但由于使用了Ajax方法而无法使用.
推荐答案
您可以通过多种方式执行此操作.
You can do this in many ways.
首先想到的是: 将按钮类型更改为按钮而不是提交,并添加onclick属性
The first that come to my mind is: change the button type to be button instead of submit and add a onclick attribute
<button type="button" onclick="submitForm('search.php')">Search</button>
<button type="button" onclick="submitForm('update.php')">Update</button>
然后在您的JavaScript中:
Then in your javascript:
function submitForm(url){
var data = $("$update-form").serialize();
$.ajax({
type : 'POST',
url : url,
data : data,
success : function(data){
$(".display").html(data);
}
});
}
这篇关于如何在具有Ajax的单个表单中使用多个Submit按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!