【问题标题】:Input button not submitting with AJAX输入按钮未使用 AJAX 提交
【发布时间】:2015-05-19 20:44:11
【问题描述】:

php 我有以下代码

<form id="one" method="POST" action="#">

<input type="text" name="rfc" />

<button type="submit" name="selection" value="1">Option 1 </button>
<button type="submit" name="selection" value="2">Option 2 </button>
<input type="submit" name="selection" value="4" />

</form>

<section id="new_section"></section>
      <script>
        $('#one').submit(function(event){
          var data = $(this).serialize();
          $.post('two.php', data)
          .success(function(result){
              $('#new_section').html(result);
          })
          .error(function(){
              console.log('Error loading page');
          })
          return false;
        });
      </script>

在 two.php 中,我验证了 rfc 和选择字段的值

两个.php

print_r($_POST);

而 print_r 只显示 rfc 而不是 selection ,输出如下:

数组([rfc] => WIRK510828)

发生这种情况是因为 action=# 吗?

【问题讨论】:

  • 我认为您应该将按钮更改为提交类型的输入。
  • 这两个&lt;button&gt;标签是干什么用的?

标签: php ajax html


【解决方案1】:

这是因为你应该单独传递按钮的值,因为 serialize() 不接受按钮的值。

首先你必须为每个按钮添加和 id 或 class 使用serializeArray(); 而不是serialize()

在你的 html 上做这样的事情,它工作我刚刚测试过:

<form id="one" method="POST" action="#">

    <input type="text" name="rfc" />

    <button type="submit" id="button1" name="selection" value="1">Option 1 </button>
    <button type="submit" id="button2" name="selection" value="2">Option 2 </button>
    <button type="submit" id="button4" name="selection" value="4">option 4</button>

</form>
<section id="new_section"></section>


<script>
var frm = $('#one');
var data = frm.serializeArray();
$('#button1, #button2, #button4').on("click",function(e) {
e.preventDefault();

frm.submit(function(event){
  $.post('two.php', data)
  .success(function(result){
      $('#new_section').html(result);
  })
  .error(function(){
      console.log('Error loading page');
  })
  return false;
});
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
frm.submit();
data.pop();
});
</script>

解释: 我使用data.push(); 将额外数据(按钮值)推送到serializeArray();,然后使用frm.submit() 发送表单,最后使用data.pop() 清理数组以备将来使用。我还添加了一些变量以更好地实现。

【讨论】: