Rac*_*oon 8 html javascript php ajax jquery
在过去的几天里,我一直在努力用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>
Run Code Online (Sandbox Code Playgroud)
我的用于获取表单值的jQuery脚本如下所示:
$("form").submit(function (event) {
$.dataArray = $(this).serializeArray(); // array of form data
console.log($.dataArray);
event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
但这会返回除图像一以外的所有字段值,如果图像返回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>
Run Code Online (Sandbox Code Playgroud)
对于多张图片,您将不得不循环不同的内容