【发布时间】:2017-05-14 00:26:14
【问题描述】:
我正在尝试通过 Ajax 设置 FormData 对象执行图像上传,但是当提交表单数据时,_FILES 变量保持为空并且 get HTTP_RAW_POST_DATA=[object Object] 不确定问题出在哪里,但非常感谢您对此的帮助。
下面的代码sn-ps:
<form id="test_upload_form" action="/inventory/fileImport">
<input id="test_file" type="file" name="superfile">
<input type="hidden" name="nonce" value="<?=$this->nonceField()?>">
<input type="submit" name="submit">
</form>
<script>
$('#test_upload_form').on('submit', function(e){
e.preventDefault();
var fileInput = $('#test_file');
debugger;
var file = ($('#test_file'))[0].files[0];
var formData = new FormData($(this));
formData.append('file', file);
$.ajax({
url: '/inventory/fileImport',
type: 'POST',
data: formData,
cache: false,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
console.log(data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
});
</script>
刚刚将 Javascript 修改为以下内容,现在似乎可以正常工作了。 只是不适用于 Jquery。
$('#test_upload_form').on('submit', function(e){
e.preventDefault();
var file = ($('#test_file'))[0].files[0];
var formData = new FormData(document.getElementById("test_upload_form"));
formData.append('file', file);
var request = new XMLHttpRequest();
request.open("POST", "/inventory/fileImport");
formData.append("serialnumber", 'asdasdsadas');
request.send(formData);
});
【问题讨论】:
-
尝试设置
dataType: 'text',如你所见here -
不行还是不行
标签: php ajax forms file upload