【问题标题】:How to process ajax form parameters with PHP script如何使用 PHP 脚本处理 ajax 表单参数
【发布时间】:2010-08-20 23:24:42
【问题描述】:

我一直在开发一个动态生成的表单,它将类似于下面示例的多个项目传递给 PHP 脚本。

<div class="menu-item">
<input type="text" value="3" readonly="readonly" class="quantity" name="quantity">
<input type="text" value="Menu Item 3" readonly="readonly" class="item" name="item">
<input type="text" value="80.00" readonly="readonly" class="price" name="price">
</div>
...etc

我的问题是因为我没有给 quantityitempricename 属性提供唯一标识符,我将这些类型的参数传递到服务器端:

quantity=3&item=Menu+Item+3&price=80.00&quantity=2&item=Menu+Item+2&price=50.00&quantity=1&item=Menu+Item+1&price=30.00&total=370.00&name=Alex&table=10&terms=on

我可以很容易地改变它,所以 names 将是数量 1、项目 1、价格 1、数量 2、项目 2、价格 2 等,但无论哪种方式,我都不确定如何最好地使用 PHP 循环这些参数集,所以我可以确保我处理了与项目对应的每个quantityitemprice

谢谢, 亚历克斯

【问题讨论】:

标签: php arrays forms


【解决方案1】:

如果您将字段命名为quantity[]item[]price[],PHP 会将它们组装成一个以每个事物命名的数组。只需确保页面上所有数量、项目和价格的顺序相同(并且没有一个会跳过一个字段),$_POST['quantity'][0] 将是第一个数量,$_POST['price'][0] 将是第一个价格,等等。

【讨论】:

  • 我很无聊。什么都不做,只是通过 SO 寻找要回答的问题和获得代表。 :)
【解决方案2】:

我通常做的事情如下:

使用以下名称生成表单:quantity-x、item-x、price-x;

这是你处理它的方式:

$values = array();
foreach($_POST AS $key => $value ){
$keyPart = explode('-',$key);
$values[$keyPart[1]][$keyPart[0]] = $value
}

这将生成一个数组,其中每个元素都包含一个包含分组值的数组。所以元素 0 将是 [quantity-1,price-1,item-1] 而元素 1 将是 [quantity-2,price-2,item-2]

这种方式的价值在于您不必跟踪元素的顺序。因为唯一标识符可以直接链接到数据库主键。缺点是,您将不得不迭代两次。

编辑:这也适用于 $_GET

【讨论】:

    【解决方案3】:

    假设您只有那些通过 GET 进入的变量,这将是一种方法:

    //number of fields/item
    $fields = 3;
    $itemCount = count($_GET) / $fields;
    
    for ($i = 1; i <= $fields; i++) {
         $quantity = $_GET['quantity'.i];
         $item = $_GET['item'.i];
         $price = $_GET['price'.i];
         processFields($quantity, $item, $price);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 2012-08-24
      • 1970-01-01
      • 2011-09-01
      相关资源
      最近更新 更多