首页 > 解决方案 > jQuery如何发布特定的值数组

问题描述

这是动态输入形式

<form role="form" method="post" id="form1">

<input type='text' id='shipping' name='shipping[3]'>
<input type='text' id='payment' name='payment[3]'>
<input type='text' id='address' name='address[3]'>

<input type='text' id='shipping' name='shipping[4]'>
<input type='text' id='payment' name='payment[4]'>
<input type='text' id='address' name='address[4]'>

<input type='text' id='option' name='option'>
</form>

我的 javascript(jQuery) 将此表单发布到 PHP-Server 端

    $.post("phpfile", $('#form1').serialize(),
    function (data) {
    }
);

如果使用序列化();它将以输入形式发布所有数据示例:

option: exampledata
shipping[4]: exampledata
payment[4]: exampledata
address[4]: exampledata
shipping[3]: exampledata
payment[3]: exampledata
address[3]: exampledata

我只想发布特定数据,例如运输地址而不是付款有什么办法吗?

shipping[4]: exampledata
address[4]: exampledata
shipping[3]: exampledata
address[3]: exampledata

标签: javascriptjqueryarraysserialization

解决方案


我要做的是声明一个数组,然后使用^=运算符,它将查找具有该名称的每个元素。然后,我将使用该.each()函数创建一个循环,该循环以我的元素计数进行迭代。然后我可以将.push()我的值放入我声明的数组中。然后,我将遍历我的另一个文件中的数组,将数据发送到“phpfile”,正如您所命名的那样。

例子:

var shippingArray = [];

$('input[name^="shipping"]').each(function() {
    shippingArray.push( $(this).val() );
});

var addressArray = [];

$('input[name^="address"]').each(function() {
    addressArray.push( $(this).val() );
});

您现在有 2 个完美的数组变量,您可以将其解析为您想要的任何文件。我建议你看看 jQuery AJAX。

所以在文件中,“phpfile”

$shippingArray=$_POST['shippingArray'];
$shippingValues=array_values($shippingArray);

$addressArray=$_POST['addressArray'];
$addressValues=array_values($addressArray);

$i=0;
$length=count($shippingArray);

while($i < $length) {
    $i++;
    $arrayValue=$shippingArray[$i];

   //Do something with the value
}

$i=0;
$length=count($addressArray);

while($i < $length) {
    $i++;
    $arrayValue=$addressArray[$i];

   //Do something with the value
}

推荐阅读