我正在尝试提交一个表单的 ajax 调用,我在其中添加了动态向表单添加输入的功能。我的表单是基于数组循环创建的,所以有时我只有一个表单,有时更多。
无论如何,我都可以使用按钮上的控制台从每个表单中转储正确的输入值,但我在 ajax 提交时收到 500 错误。
一个问题是,如果我在表单中有 4 个输入,我将转储所有 4 个,然后转储我的一个隐藏输入值“tickerID”,但我正在调用一个 sql 插入,我需要在其中插入每个值隐藏的输入值。
但我需要将它们插入为
insert into ticker_content (ticker_id, content)
values (1, 'one'), (1, 'two');
如果这是有道理的。
这是为插入而调用的我的 addticker.php:
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
foreach ($items as $item){
$addTicker = "
INSERT INTO ticker_content (tickerID, content)
values ('$tickerID', '$item');
"
$mysqlConn->query($addTicker);
}
所以基本上对于每个 Items[] 值,我都需要插入相同的隐藏字段。
这是我的表单和 JS 代码以供引用。第一个JS block 主要是动态添加输入的功能,最后一个JS block 是使用serializeArray()的ajax;
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/> <!--form starts with one input-->
<button type="button" class="moreItems_add">+</button> <!--button dynamically adds input, up to 10 per form-->
<input type="hidden" name="tickerID" id="tickerID" class="tickerIdClass" value="<?php echo $ticker['ticker'] ?>"><!--hidden input used for tickerID-->
<input type="submit" name="saveTickerItems" value="Save Ticker Items"> <!--submit button-->
</form>
<?php endforeach;?>
<!-- This is the functionality for each form to click the '+' button and create new inputs -->
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $(this).closest('form').find('.tickerIdClass').val(); //get value of hidden input for form
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
<!-- This is the ajax call to send all filled out and created inputs from form along with the hidden input -->
<script type="text/javascript">
$("#Items").submit(function(e) {
e.preventDefault();
var data = $("#Items").serializeArray();
console.log(data);
$.ajax({
type: "POST",
url: "addticker.php",
data: $("#Items").serializeArray(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
最佳答案
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
$value = "";
foreach ($items as $item){
$value .= "('$tickerID', '$item'),";
}
$addTicker = "INSERT INTO ticker_content (tickerID, content)
values {$value}";
$mysqlConn->query($addTicker);
使用此代码
关于javascript - 使用 serializeArray,尝试从 ajax 插入多个输入,每个输入都有 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52313553/