PHP 中的无限字段?

发布于 2024-07-25 05:29:33 字数 255 浏览 10 评论 0原文

如何在php中实现无限字段? 场景如下:

首先,只有 2 个字段,我们称之为:名字 1,姓氏 1

我想要做的是,当我单击“添加”按钮时,它将在新行中添加另外 2 个字段,即字段标签/名称应为名字 2、姓氏 2。 当我再次单击时,它将显示名字 3、姓氏 3 等等。

任何人都可以给我一些 php 示例脚本吗? 我是 PHP 新手。

该表单应采用 HTML 格式。 如果有人可以提供 Ajax 示例代码,那就太好了。

How do I do unlimited fields in php? Here is the scenario:

At first, there are only 2 fields, lets called: first name1, last name1

What I want to do is, when I click the "add" button, it will add another 2 fields in new row, the fields label/name should be first name2, last name2. And when I click again, it will have first name3, last name3, and so on..

Can anyone give me some sample script in php? I am new to PHP.

The form should be in HTML. If somebody can give Ajax sample code, would be a big plus.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浪荡不羁 2024-08-01 05:29:33

这取决于你所说的“场”是什么意思。 听起来好像你在谈论一个表单,它不是 PHP,而是 HTML。 您可以将按钮 [添加] 发送回服务器,然后使用另一组表单输入刷新页面。 您还可以通过 javascript 执行此操作,而无需刷新页面。

简单 Javascript (jQuery) 示例:

$(document).ready(function(){
  $("input[value='Add']").click(function(event){
    event.preventDefault();
    $("p.field:last").clone().insertAfter("p.field:last");
  });
});

<form method="post">
  <p class="field">
    <input type="text" name="firstname[]" value="" /> 
    <input type="text" name="lastname[]" value="" />
  </p>
  <p>
    <input type="submit" name="submit" value="Add" /> 
    <input type="submit" name="submit" value="Done" />
  </p>
</form>

简单 PHP 示例:

我不鼓励您按原样使用此

<?php

  $count = 1;

  if ($_POST["submit"] == "Add") {

    $count = ($_POST["firstname"]) ? (count($_POST["firstname"]) + 1) : 1;

  } else 
  if ($_POST["submit"] == "Done") {

    print "<pre>";
    print_r($_POST["firstname"]);
    print_r($_POST["lastname"]);
    print "</pre>";

  }

?>
<form method="post">
  <?php for($i = 0; $i < $count; $i++) { ?>
  <p class="field">
    <input type="text" name="firstname[]" value="<?php print $_POST["firstname"][$i]; ?>" /> 
    <input type="text" name="lastname[]" value="<?php print $_POST["lastname"][$i]; ?>" />
  </p>
  <?php } ?>
  <p>
    <input type="submit" name="submit" value="Add" /> 
    <input type="submit" name="submit" value="Done" />
  </p>
</form>

That depends on what you mean by "field." It sounds as though you're talking about a form, which wouldn't be PHP, but instead HTML. You could have a button [Add] post back to the server, which then refreshes the page with another set of form-inputs. You also do that via javascript without having to refresh the page.

Simple Javascript (jQuery) Example:

$(document).ready(function(){
  $("input[value='Add']").click(function(event){
    event.preventDefault();
    $("p.field:last").clone().insertAfter("p.field:last");
  });
});

<form method="post">
  <p class="field">
    <input type="text" name="firstname[]" value="" /> 
    <input type="text" name="lastname[]" value="" />
  </p>
  <p>
    <input type="submit" name="submit" value="Add" /> 
    <input type="submit" name="submit" value="Done" />
  </p>
</form>

Simple PHP Example:

I don't encourage you use this as-is

<?php

  $count = 1;

  if ($_POST["submit"] == "Add") {

    $count = ($_POST["firstname"]) ? (count($_POST["firstname"]) + 1) : 1;

  } else 
  if ($_POST["submit"] == "Done") {

    print "<pre>";
    print_r($_POST["firstname"]);
    print_r($_POST["lastname"]);
    print "</pre>";

  }

?>
<form method="post">
  <?php for($i = 0; $i < $count; $i++) { ?>
  <p class="field">
    <input type="text" name="firstname[]" value="<?php print $_POST["firstname"][$i]; ?>" /> 
    <input type="text" name="lastname[]" value="<?php print $_POST["lastname"][$i]; ?>" />
  </p>
  <?php } ?>
  <p>
    <input type="submit" name="submit" value="Add" /> 
    <input type="submit" name="submit" value="Done" />
  </p>
</form>
山色无中 2024-08-01 05:29:33

有两种方法可以做到这一点,要么单独使用 PHP,要么使用一些奇特的 JavaScript。 我将解决仅 PHP 的解决方案。 JavaScript 解决方案的响应速度会更快,因为不会重复往返服务器,但它也只适用于启用了 JavaScript 的用户,而 PHP 解决方案适用于所有人。

解决方案的概要如下:

  1. 最初$count 为1,并生成一行。
  2. 如果用户单击“添加”,表单将被发送回同一个 PHP 文件,其中包含一个隐藏的 count 变量。 该脚本从头开始重新启动,递增 $count,并比上次多显示一行。
  3. 如果用户单击“提交”,则会处理已输入的名称。

这是一些示例代码。 很抱歉,我正在编写此程序的计算机上没有安装 PHP,因此完全未经测试。 希望没有太多可怕的语法错误!

<?php
  $count = isset($_POST['count']) ? $_POST['count'] : 1;

  if (isset($_POST['add']))
    ++$count;
  else if (isset($_POST['submit']))
  {
    header('Content-Type: text/plain');
    print_r($_POST);
    exit;
  }
?>

<html>
  <body>
    <form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']) ?>" method="post">
      <input type="hidden" name="count" value="<?php echo $count ?>" />

      <?php for ($i = 1; $i <= $count; ++$i) { ?>

        [<?php echo $i ?>]
        First: <input type="text" name="firstName<?php echo $i ?>"
                      value="<?php echo htmlspecialchars($_POST["firstName$i"]) ?>" />
        Last:  <input type="text" name="lastName<?php echo $i ?>"
                      value="<?php echo htmlspecialchars($_POST["lastName$i"]) ?>" />
        <br />

      <?php } ?>

      <input type="submit" name="add"    value="Add"    />
      <input type="submit" name="submit" value="Submit" />
    </form>
  </body>
</html>

哦,你想要一个 JavaScript 解决方案,是吗? 好吧,你已经得到了非常好的 jQuery 答案。 那么,一个长得可笑的纯 JavaScript 解决方案怎么样?

<html>
  <head>
    <script type="text/javascript">
    // <![CDATA[

      var count = 0;

      function addRow() {
        var table      = document.getElementById("table");
        var row        = document.createElement("tr");
        var countCell  = document.createElement("td");
        var countText  = document.createTextNode(++count);
        var firstCell  = document.createElement("td");
        var firstInput = document.createElement("input");
        var lastCell   = document.createElement("td");
        var lastInput  = document.createElement("input");

        firstInput.type = "text";
        firstInput.name = "firstName" + count;
        lastInput.type  = "text";
        lastInput.name  = "lastName" + count;

        table    .appendChild(row);
        row      .appendChild(countCell);
        countCell.appendChild(countText);
        row      .appendChild(firstCell);
        firstCell.appendChild(firstInput);
        row      .appendChild(lastCell);
        lastCell .appendChild(lastInput);
      }

    // ]]>
    </script>
  </head>

  <body>
    <form action="somewhere.php" method="post">
      <table id="table">
        <tr>
          <th>Row</th>
          <th>First</th>
          <th>Last</th>
        </tr>
      </table>

      <script type="text/javascript">
        addRow();
      </script>

      <input type="button" value="Add" onclick="addRow()" />
      <input type="submit" value="Submit" />
    </form>
  </body>
</html>

There are two ways to do this, either using solely PHP or by some fancy JavaScript. I will tackle the PHP-only solution. A JavaScript solution would be much more responsive as there wouldn't be repeated round trips to the server but it would also only work for users who have JavaScript enabled, whereas a PHP solution works for everybody.

A general outline of the solution is this:

  1. Initially $count is 1, and one row is generated.
  2. If the user clicks Add, the form is posted back to the very same PHP file with a hidden count variable included. The script restarts from the beginning, increments $count, and displays one more row than the last time.
  3. If the user clicks Submit, the names that have been entered are processed.

Here's some sample code. I apologize that I do not have PHP installed on the machine I'm writing this one so this is entirely untested. Hopefully there aren't too many horrendous syntax errors!

<?php
  $count = isset($_POST['count']) ? $_POST['count'] : 1;

  if (isset($_POST['add']))
    ++$count;
  else if (isset($_POST['submit']))
  {
    header('Content-Type: text/plain');
    print_r($_POST);
    exit;
  }
?>

<html>
  <body>
    <form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']) ?>" method="post">
      <input type="hidden" name="count" value="<?php echo $count ?>" />

      <?php for ($i = 1; $i <= $count; ++$i) { ?>

        [<?php echo $i ?>]
        First: <input type="text" name="firstName<?php echo $i ?>"
                      value="<?php echo htmlspecialchars($_POST["firstName$i"]) ?>" />
        Last:  <input type="text" name="lastName<?php echo $i ?>"
                      value="<?php echo htmlspecialchars($_POST["lastName$i"]) ?>" />
        <br />

      <?php } ?>

      <input type="submit" name="add"    value="Add"    />
      <input type="submit" name="submit" value="Submit" />
    </form>
  </body>
</html>

Oh and you want a JavaScript solution, eh? Well you've got the really nice jQuery answer already. How about a ridiculously long plain-JavaScript solution, then?

<html>
  <head>
    <script type="text/javascript">
    // <![CDATA[

      var count = 0;

      function addRow() {
        var table      = document.getElementById("table");
        var row        = document.createElement("tr");
        var countCell  = document.createElement("td");
        var countText  = document.createTextNode(++count);
        var firstCell  = document.createElement("td");
        var firstInput = document.createElement("input");
        var lastCell   = document.createElement("td");
        var lastInput  = document.createElement("input");

        firstInput.type = "text";
        firstInput.name = "firstName" + count;
        lastInput.type  = "text";
        lastInput.name  = "lastName" + count;

        table    .appendChild(row);
        row      .appendChild(countCell);
        countCell.appendChild(countText);
        row      .appendChild(firstCell);
        firstCell.appendChild(firstInput);
        row      .appendChild(lastCell);
        lastCell .appendChild(lastInput);
      }

    // ]]>
    </script>
  </head>

  <body>
    <form action="somewhere.php" method="post">
      <table id="table">
        <tr>
          <th>Row</th>
          <th>First</th>
          <th>Last</th>
        </tr>
      </table>

      <script type="text/javascript">
        addRow();
      </script>

      <input type="button" value="Add" onclick="addRow()" />
      <input type="submit" value="Submit" />
    </form>
  </body>
</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文