PHP使用jQuery .post()提交带有多个提交按钮的表单

我有以下HTML代码:

<input type="text" name="the_input" value="">

接着是这个JS:

 $('#the-form').bind('submit', submitForm); function submitForm(evt) { jQuery.post( $(this).attr('action'), $(this).serialize(), function(data) { $('#result').empty().append(data).slideDown(); }); evt.preventDefault(); } 

我还有一个PHP脚本,它从提交时的输入接收$ _POST值并运行条件来测试单击了哪个提交按钮。

像这样:

 $input = $_POST['the_input']; $eating = $_POST['eat_something']; if ( $eating == 'TRUE' ) { // Do some eating... } else { // Don't you dare... } 

如果我不使用jQuery.post()函数,则会发布按钮的提交值。 但是,出于某种原因,我无法使用jQuery.post()函数将按钮值传递给PHP $ _POST。 如果我不使用jQuery.post(),则输出不会附加到textarea,而是以文本格式附加到单独的页面上,如文档。 我也尝试在$('button[type=submit]').bind('submit', submitForm);上调用提交函数$('button[type=submit]').bind('submit', submitForm); 但这也无法解决我的问题。

在此先感谢您的帮助。

您忘记了在the_name输入中的the_name quote和)

  

并且要获取表单按钮按下的值,您需要手动附加值以序列化。

 $form.serialize() + "&submit="+ $('button').attr("value") 

  

完整的测试代码

      StackOverFlow     

最简单的答案是:

 

当然,这并不能完全满足您的需求。

你也可以这样做:

 
$('#the-form button').bind('click', function(){ jQuery.post($('#the-form').attr('action'), { the_input: $('#theInput').val(), eat_something: $(this).attr('data-value') }, function(data) { $('#result').empty().append(data).slideDown() }, 'json' });

将按钮更改为此(更改w /您的表单名称)..

    

Javascript函数和PHP都很好。

谢谢!

@leo