有没有办法将通过FormData
创建的javascript
附加到常规的<form>
POST操作中?
我有一个“旧式”<form>
,它提交重新加载整个页面,没有任何花哨的Ajax
噱头。我想要的是能够使用一个漂亮的文件上传脚本,利用拖动和放大删除和图像预览,同时保留旧的表单行为。
到目前为止,所有脚本仅用于创建FormData
对象并向其附加数据,但我发现无法将检索到的信息添加到经典表单POST
请求中。
有谁知道这样做的方法?谢谢。
编辑:对不起,伙计们,花了一些时间来提取并测试一个正常工作的代码原型:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form enctype="multipart/form-data" class="form" id="image_form" method="post" action="http://www.mysite.local/upload_image.php">
<div id="dropbox">Drag your image here</div>
Or try old-style upload:<br />
<input type="file" id="upload_input" name="new_image">
<button id="upload_btn" type="submit">Upload file!</button>
</form>
<script type="text/javascript">
var form_data = new FormData(document.getElementById('image_form'));
$('#dropbox').on('drag dragstart dragend dragover dragenter dragleave drop', function(e) {
e.preventDefault(); // just so that drag&drop works
e.stopPropagation(); // just so that drag&drop works
})
.on('drop', function(e) {
$.each( e.originalEvent.dataTransfer.files, function(i, file) {
form_data.append("new_image", file); // appending file to form_data
});
// form_data is now Ajax ready, but the form knows nothing about it
// upon submitting the form, the information won't be a part of $_POST
});
</script>