javascript - 如何使用 ajax 将与每个按钮相关的数据发送到 php?

标签 javascript php jquery ajax

我知道像这样的代码用于将数据发送到 php 文件而不使用 ajax 刷新,但这段代码仅适用于具有某些输入的一种表单,我的问题是: 我有一个网页,里面有 5 个按钮,每个按钮都与不同的输入相关,我想用 ajax 发送数据而不刷新,例如当我点击按钮 1 时,它发送自己的输入,当我点击按钮时n 它发送自己的数据,我该怎么做?

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

    $('form').on('submit', function (e) {

      e.preventDefault();

      $.ajax({
        type: 'post',
        url: 'led.php',
        data: $('form').serialize(),
        success: function () {
        }
      });

    });

  });
   </script>
 </head>
 <body>
    <form>
      <input type='hidden' name="key" value="on">
      <input name="key" type="submit" value="ON">
    </form>
  </body>
</html>

最佳答案

" but this code only works for one form with some inputs "

从技术上讲,这将适用于页面上的任何表单。 (因为您的目标是 form 标签)

如果您想定位多个按钮并以相同的方式处理它们,请向它们添加一个类。

如果您想单独定位单独的元素,请添加一个 id。

然后您将类定位为 $('.classname') 并将 id 定位为 $('#id') 注意 .和 #(与 css 选择器一样)

SEE LIVE EXAMPLE here

$('.submit_to_a').parent('form').on('submit', function(e) {

  e.preventDefault();

  $.ajax({
    type: 'post',
    url: 'a.php',
    data: $(this).serialize(),
    success: function() {}
  });

});


$('#gotob').parent('form').on('submit', function(e) {

  e.preventDefault();

  $.ajax({
    type: 'post',
    url: 'b.php',
    data: $(this).serialize(),
    success: function() {}
  });

});

$('#gotoc').parent('form').on('submit', function(e) {

  e.preventDefault();

  $.ajax({
    type: 'post',
    url: 'c.php',
    data: $(this).serialize(),
    success: function() {}
  });

});
<form action="a.php">
  <input type="text">
  <input type="text">
  <input type="text">
  <button type="submit" class="submit_to_a">goes to a</button>
</form>
<form action="a.php">
  <input type="text">
  <input type="text">
  <input type="text">
  <button type="submit" class="submit_to_a">goes to a</button>
</form>
<form action="b.php">
  <input type="text">
  <input type="text">
  <input type="text">
  <button type="submit" id="gotob">goes to b</button>
</form>
<form action="c.php">
  <input type="text">
  <input type="text">
  <input type="text">
  <button type="submit" id="gotoc">goes to c</button>
</form>

关于javascript - 如何使用 ajax 将与每个按钮相关的数据发送到 php?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27676052/

相关文章:

javascript - 从 firebase 函数读取数据

PHP DateTime 接受多种格式?

php - 如何发送退款请求?

php - 在Symfony的生产模式下使用PHP的内置Web服务器

javascript - 当我在它外面的任何地方关闭时关闭侧面板

javascript - 未捕获的类型错误 : Cannot call a class as a function in react and redux

javascript - 使用 JavaScript/PHP 每 5 秒刷新一次 DIV

javascript - HtmlUnit - 如何显示 iframe 内容

jQuery addClass 属性出现然后消失

jquery - 使用 jquery 显示图像的一部分