我试图创建一个多插入表格,您可以通过填写数字来插入任意数量的图块和相关语言。标题和语言的显示效果很好,但是我无法获取不同的值并将其插入db。我的目的是使每个带有Lang的Title在数据库中都具有唯一的ID。
<form method="POST" action="" enctype="multipart/form-data">
<table>
<tr>
<th>Title</th>
<th>Language</th>
</tr>
</table>
<input id="count" type="number" placeholder="Number of Titles">
<input type="button" id="plus" value="+">
<input type="submit" id="save" name="save" value="Save">
<script type="text/javascript">
$('#plus').on('click', function(){
var queryString = "";
var count = $('#count').val();
var i;
for(i = 1; i <= count; i++){
$('table').append('<tr><td><input name="title" type="text" placeholder="Title" id="Title_'+i+'" autocomplete="off" class="title"></td><td><select name="lang" id="Lang_'+i+'"><option value="0">Romaji</option><option value="ja">Japanese</option><option value="en">English</option><option value="de">German</option><option value="ru">Russian</option></select></td></tr>');
}
});
$('#save').on('click', function(){
var Title = $('#Title_'+i).val();
console.log(Title);
queryString ='title='+Title+'&lang='+Lang;
jQuery.ajax({
url: "action/insert.php",
data: queryString,
type: "POST",
success:function(data){
location.reload();
},
});
});
</script>
</form>
我还尝试通过Jquery获取输入的值,并将其与Jquery Ajax一起发送到PHP文件,但是当我尝试在控制台中显示值时,我只会得到输出“ undefined”
insert.php
<?php
require "../config.php";
$title= $_POST['title'];
$lang= $_POST["lang"];
$sql = "INSERT INTO MyGuests (title, lang) VALUES ('".$_POST['']."', '".$_POST['']."');";
$sql .= "INSERT INTO MyGuests (title, lang) VALUES ('".$_POST['']."', '".$_POST['']."');";
$sql .= "INSERT INTO MyGuests (title, lang) VALUES ('".$_POST['']."', '".$_POST['']."')";
...
mysqli_multi_query($conn, $sql);
?>
答案 0 :(得分:1)
JavaScript
<script type="text/javascript">
$(document).ready(function(){
var input = '<input type="text" placeholder="Title" autocomplete="off" class="title">';
var select = '<select><option value="0">Romaji</option><option value="ja">Japanese</option><option value="en">English</option><option value="de">German</option><option value="ru">Russian</option></select>';
var i = 1;
$('#plus').on('click', function(){
var tr = $('tr');
var td1 = $('td');
var td2 = $('td');
td1.append($(input).attr('name', 'myguest['+i+'][title]').attr('id','Title_'+i));
td2.append($(select).attr('name', 'myguest['+i+'][lang]').attr('id','Lang_'+i));
tr.append(td1).append(td2);
$('table').append(tr);
i++;
});
});
</script>
PHP方面
<?php
foreach($_POST['myguest'] as $guest) {
$sql = "INSERT INTO MyGuests (title, lang) VALUES ('".$guest['title']."', '".$_POST['lang']."');";
mysqli_query($conn, $sql);
}
别忘了从post中删除值
答案 1 :(得分:0)
您需要遍历所有#Title_<something>
项:
var titles = $('[id^=Title_]');
titles.each(function() {
console.log(this.val());
// do other things
});
请参见Wildcards in jQuery selectors 和how to iterate a result of jquery selector