在过去的几天里,我一直在努力使用 jQuery 和 AJAX 提交表单。我面临的问题是在表单字段中上传图片。
我的表格是这样的:
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
我获取表单值的 jQuery 脚本是这样的:
$("form").submit(function (event) {
$.dataArray = $(this).serializeArray(); // array of form data
console.log($.dataArray);
event.preventDefault();
});
但这会返回除图像一以外的所有字段值,如果图像返回 null。
如何存储在数据数组中?
我想存储以便通过 AJAX 将值发送到服务器。
最佳答案
上传单张图片是这样的
<html>
<head>
<meta charset="UTF-8">
<title>AJAX image upload with, jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://localhost/ci/index.php/welcome/upload', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
</head>
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" multiple />
<button id="upload">Upload</button>
</body>
</html>
对于多个图像,你将不得不循环它有点不同
关于javascript - 如何通过jQuery上传图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44283986/