我想提交一份表格。像这样它运作得很好:
<form>
<input name="name" value="somebody"><br>
<button type="submit" name="action" value="Submit" name="submit" >Submit</button>
</form>
<script>
$(document).on('submit','form',function(e){
e.preventDefault();
$form = $(this);
submit($form);
});
function submit($form){
...do something....
}
</script>
但我的页面上有多个表单,所以我想尝试这样的事情:
<form name="myform">
<input name="name" value="somebody"><br>
<button type="submit" name="action" value="Submit" name="submit" >Submit</button>
</form>
<script>
$(document).on('submit','myform',function(e){
e.preventDefault();
$form = $(this);
submit($form);
});
function submit($form){
$.ajax('action.php', {
method: 'POST',
data: $form.serialize(),
success: function(result) {
$('#result').html(result);
}
});
}
</script>
但遗憾的是,这不起作用。你知道为什么吗?
答案 0 :(得分:1)
这应该让你开始。每个表单提交也可以有不同的功能。
function submit($form, action) {
alert("Submitting form");
$.ajax(action, {
method: 'POST',
data: $form.serialize(),
success: function(result) {
$('#result').html(result);
}
})
}
// Shorthand for $( document ).ready()
$(function() {
$("#btn1").click(function() {
alert("Submitting form 1");
submit($("#frm1"), 'action1.php');
});
$("#btn2").click(function() {
alert("Submitting form 2");
submit($("#frm2"), 'action2.php');
$("#frm1").submit();
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="frm1" name="frm1">
<input name="name" value="somebody">
<br>
<button type="submit" id="btn1" name="btn1" value="Submit">Submit Form 1</button>
</form>
<br>
<br>
<form id="frm2" name="frm2">
<input name="name2" value="somebody else">
<br>
<button type="submit" id="btn2" name="btn2" value="Submit">Submit Form 2</button>
</form>
&#13;