javascript - Javascript通过循环从输入中收集值
问题描述
这是代码部分:
<td style="vertical-align: middle; white-space: nowrap; text-align: right;">
<input type="text" id="comment" name="com" placeholder="Enter comment">
</td>
这部分为我提供了与添加到购物车中的产品一样多的输入字段,这就是它们通过循环的原因。
然后我尝试用这个收集这些输入的值:
var comment = document.getElementsByName("com").value;
并将其转发:
jQuery.ajax({
type: "POST",
async: true,
url: "/content/shop/order_process/ajax_checkout_create.php",
dataType: "json",
data: "item_comment="+encodeURIComponent(comment),
success: function(answer)
{
if(answer.status == true)
{
<?php
if($user_id != 0)
{
?>
location = "/shop/orders/order?order_id="+answer.order_id+"&success_message="+encodeURI("Order created");
<?php
}
else
{
?>
location = "/shop/orders/orders-without-reg";
<?php
}
?>
}
else
{
alert(answer.message);
document.getElementById("confirm_loader").style.display = 'none';
document.getElementById("confirm_btn").style.display = 'inline';
return false;
}
}
});
最后一部分在这个文件中/content/shop/order_process/ajax_checkout_create.php
有一个代码需要收集所有输入的值并存储在数据库中:
if( !empty($_POST["item_comment"]) )
{
$item_comment = trim($_POST["item_comment"]);
$item_comment = htmlentities($item_comment);
$item_comment = str_replace("\r","",$item_comment);
$item_comment = str_replace("\t","",$item_comment);
$item_comment = str_replace("\n","<br/>",$item_comment);
$db_link->prepare('INSERT INTO `shop_orders_items_comment` (`order_id`, `order_item_id`, `text`) VALUES (?,?,?);')->execute( array($order_id, $order_item_id, $item_comment) );
}
目前,我只能获得一条评论,即第一条,但我如何才能获得所有评论呢?
解决方案
首先 - 您正在重写相同的变量。第二个,你必须作为数组发送,你可以如何制作一个数组:
<input type="text" name="com" placeholder="Enter comment">
<input type="text" name="com" placeholder="Enter comment">
<input type="text" name="com" placeholder="Enter comment">
<button onclick="parse_data();">parse</button>
<script>
function parse_data(){
let elems = document.getElementsByName("com");
let data = [];
[...elems].forEach(function(item){
if (item.value.length > 0){
data.push(item.value);
}
});
console.log(data);
}
</script>
那么您必须将 item_comment 作为数组发送并在 PHP 中进行处理:
<?PHP
if (array_key_exists('item_comment', $_POST)){
foreach($_POST['item_comment'] as $value){
print($value.PHP_EOL);
}
}
例如:
curl -X POST -d "item_comment[]=1&item_comment[]=2" https://localhost/tests/form.php --insecure
将返回:
1
2
它只是示例,您应该为您的代码返工
推荐阅读
- javascript - OpenLayers RenderComplete 事件回调在回调中使用此上下文
- flutter - GpuDelegateV2 Tflite 不接受任何参数
- python - 有没有办法使用 Selenium 绕过在 cookie 弹出窗口上单击“接受 Cookie”,然后单击其后面的“添加到购物车”按钮?
- pine-script - 如何进行追踪止损或条件止损?这是我的代码
- javascript - 如何在 vue.js 中动态添加新的数据元素
- java - 错误http 404时如何在tomcat 7.0.47上部署Web服务Spring Boot
- amazon-web-services - LambdaContext 对象没有属性 getRemainingTimeInMillis
- ruby-on-rails - 跳过 devise-secure_password password_has_required_content 模块
- database - 序列号与自我实现
- react-native - 在选项卡1上显示的活动指示器以及选项卡2(我只希望将其显示在选项卡2上 - 当卡2加载时)