javascript - 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
解决方案
我要做的是声明一个数组,然后使用^=
运算符,它将查找具有该名称的每个元素。然后,我将使用该.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
}
推荐阅读
- ios - tableView 编辑模式删除按钮(减号)没有响应点击 - 我该如何解决这个问题?
- php - 如何将查询字符串添加到 Laravel 视图
- swift - 如何在两个“地方”获取 Firebase 数据?
- location - 切换 IsFloat 时,QDockWidget 不记得浮动大小和位置
- scala - 如果找不到匹配,则将 findFirstMatchIn 设置为忽略行-spark-scala
- apache-spark - 如何在结构化流中保持和重置状态?
- android - 如何在 AIDE 中使用 Room?
- javascript - 如何在 React 中访问孩子的状态?(反应钩子)
- bitbucket-pipelines - bitbucket 管道部署批准
- python - 解析 find 的输出