jQuery提交带有2个提交按钮的Ajax表单 [英] jQuery submit ajax form with 2 submit buttons
问题描述
im试图实现以下目标,在php中,我有这样的形式:
im trying to achieve the following, in php i have a form like this:
<form method="post" id="form_1" action="php.php">
<input type="submit" value="add" name="sub"/>
<input type="submit" value="envoi" name="sub"/>
</form>
表单操作文件为:
<?php
if( $_POST["sub"]=="add"){ ?>
<script>
alert("")
</script>
<?php echo "ZZZZZZ"; ?>
<?php } ?>
因此,这意味着如果我按带值的sub会出现警报提示,我该如何做同样的事情(区分两个提交),但使用Ajax请求:
so this means if i press sub with value add an alert prompt will come up, how can i do the same thing(differentiate both submit) but using a Ajax request:
以下代码不起作用:
$(function(){
$('form#form_1').submit(function(){
var _data= $(this).serialize()
$.ajax({
type: 'POST',
url: "php.php?",
data:_data,
success: function(html){
$('div#1').html(html)
}
})
})
})
</script>
</head>
<body>
<div id="1" style="width: 100px;height: 100px;border: 1px solid red"></div>
<form method="post" id="form_1" action="javascript:;">
<input type="submit" value="add" name="sub"/>
<input type="submit" value="envoi" name="sub"/>
</form>
</body>
推荐答案
您可以将事件处理程序放在按钮上而不是窗体上.从表单中获取参数,然后为按钮添加参数,然后发布表单.确保处理程序返回"false".
You could put the event handler on the buttons instead of on the form. Get the parameters from the form, and then add a parameter for the button, and post the form. Make sure the handler returns "false".
$(function() {
$('input[name=sub]').click(function(){
var _data= $('#form_1').serialize() + '&sub=' + $(this).val();
$.ajax({
type: 'POST',
url: "php.php?",
data:_data,
success: function(html){
$('div#1').html(html);
}
});
return false;
});
});
您必须显式添加"sub"参数,因为当您调用"serialize()"时,jQuery不包含那些参数.
You have to explicitly add the "sub" parameter because jQuery doesn't include those when you call "serialize()".
这篇关于jQuery提交带有2个提交按钮的Ajax表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!