我有一个包含多个输入数据和4个输入图像的表单,我如何使用Ajax发布它们?这是我试过的代码集...
的 HTML
<form action="<?php echo base_url('link')?>/to/controller" method="POST" id="frm-update" enctype="multipart/form-data">
<!-- Normal Post -->
<input type="text" name="input1" id="input1" class="form-control">Normal Input1
<input type="text" name="input2" id="input2" class="form-control">Normal Input2
<input type="text" name="input3" id="input3" class="form-control">Normal Input3
<input type="text" name="input4" id="input4" class="form-control">Normal Input4
<!-- Image Post -->
<input type="file" name="image1" id="image1" class="form-control">Image 1
<input type="file" name="image2" id="image2" class="form-control">Image 2
<input type="file" name="image3" id="image3" class="form-control">Image 3
<input type="file" name="image4" id="image4" class="form-control">Image 4
<button type="submit" class="btn btn-success">Save
Jquery的
<script>
$("#frm-update").validate({
ignore: ':hidden:not(.chzn)',
errorPlacement: function (error, element) {
if (element.is(":hidden")) {
element.next().parent().append(error);
} else {
error.insertAfter(element);
}
},
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: $("#frm-update").attr('action'),
data: $("#frm-update").serialize(),
</script>
我一直在想的是,如果我使用新的FormData(this),我的表单上的所有输入都会被保存吗?还是仅仅是形象?
答案 0 :(得分:0)
使用FormData
代替serialize()
$("#frm-update").validate({
ignore: ':hidden:not(.chzn)',
errorPlacement: function (error, element) {
if (element.is(":hidden")) {
element.next().parent().append(error);
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) {
var data = new FormData(form);
$.ajax({
url: $(form).attr('action'),
data: data,
type: 'POST',
contentType: false,
processData: false,
success: function (data) {
// data passed from php
console.log(data);
}
});
}
});
然后在您的PHP
中,您可以执行以下操作
<?php
// get values of input through $_POST
// move uploaded files to a directory with move_uploaded_file() function
// get inputs using $_POST
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
$input3 = $_POST['input3'];
$input4 = $_POST['input4'];
// get files using $_FILES
$image1 = $_FILES['image1']['name'];
$image2 = $_FILES['image2']['name'];
$image3 = $_FILES['image3']['name'];
$image4 = $_FILES['image4']['name'];
// save values to the database
?>