我尝试使用ajax将克隆表单中的输入插入到数据库中。当我点击“提交”按钮时,它会继续说“数据已插入”。但实际上它并没有进入数据库。
这是html
<div class="modal fade" id="skills_dialog" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span class="glyphicon glyphicon-list"></span> Add Skills</h4>
</div>
<div class="modal-body">
<form id="skill_form" method="post" action="skill/add.php">
<div class="textbox-wrapper">
<div class="input-group">
<input type="text" name="skills[]" class="form-control" style="margin-bottom:7px;"/>
<span class="input-group-btn">
<button type="button" class="btn btn-success add-textbox"><i class="glyphicon glyphicon-plus"></i></button>
</span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="addSkills" class="btn btn-default">Add</button>
</div>
</div>
</div>
</div>
用于jquery部分
<script type="text/javascript">
$(document).ready(function() {
var max = 10;
var cnt = 1;
$(".add-textbox").on("click", function(e){
e.preventDefault();
if(cnt < max){
cnt++;
$(".textbox-wrapper").append('<div class="input-group"><input type="text" name="skills[]" class="form-control" style="margin-bottom:7px;"/><span class="input-group-btn"><button type="button" class="btn btn-danger remove-textbox"><i class="glyphicon glyphicon-minus"></i></button></span></div>');
}
});
$(".textbox-wrapper").on("click",".remove-textbox", function(e){
e.preventDefault();
$(this).parents(".input-group").remove();
cnt--;
});
});
</script>
处理技能输入的Jquery
<script>
/* must apply only after HTML has loaded */
$(document).ready(function () {
$("#skill_form").on("submit", function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#skills_dialog .modal-header .modal-title').html("Result");
$('#skills_dialog .modal-body').html(data);
$("#addSkills").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
$("#addSkills").on('click', function() {
$("#skill_form").submit();
});
});
</script>
<script>
$('textarea.expand').focus(function () {
$(this).animate({ height: "4em" }, 500);
});
</script>
最后是插入查询
<?php
session_start();
$user = $_SESSION['user_name'];
error_reporting(0);
include('includes/db.php');
if($_POST){
$number = count($_POST["skills"]);
if($number > 0)
{
for($i=0; $i<$number; $i++)
{
if(trim($_POST["skills"][$i] != ''))
{
$sql = "INSERT INTO skills(user, skills) VALUES('$user','".$_POST["skills"][$i]."')";
mysql_query($sql);
}
}
echo "Data Inserted";
}
else
{
echo "Please Enter Skill(s)";
}
}
?>