我正在尝试使用 jQuery 触发表单提交,然后使用 AJAX 调用将处理文件并返回响应的 PHP 脚本。但是,问题在于提交表单后文件未上传。
HTML:
<div id="browseButton" class="step1Button" onclick="browseFile()">Browse</div>
<form method="post" id="fileForm" style="display:inline-block;">
<input id="browseInput" type="file" name="FileInput" style="display: none"/>
<label for="upload-click-handler"></label>
<input id="upload-click-handler" type="text" readonly />
<input id="submitForm" type="submit" style="display: none"/>
</form>
<div id="previewButton" class="step1Button pull-right" onclick="uploadFile()" style="background-color: #57a957">
Preview
</div>
jQuery:
function uploadFile() {
submitForm();
parseExcel();
}
var submitForm = function() {
$('#previewButton').click(function(){
$('#submitForm').click();
});
};
var parseExcel = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",'default/ParseExcel',true);
xmlhttp.send();
console.log("made it past excel parse");
};
调用的 PHP:
public function actionParseExcel() {
print "made it to parse".PHP_EOL;
print "File:";
if($_FILES['FileInput']['tmp_name']) {
print_r($_FILES['FileInput']['tmp_name']);
}
else {
print "Not found";
}
print "Done.";
}
我知道问题是我的表单没有提交所选文件,因为这通常是抛出“未定义索引”错误的原因。但我不明白为什么。
最佳答案
首先,如果你不想刷新你的页面,你最好使用<input type="button">
或者通过 <form onSubmit="uploadFile()">
调用你的 JavaScript和 return false
在函数 uploadFile() 的末尾。
其次,您需要输入 enctype="multipart/form-data"
在你的<form>
.
我看到您正在使用 JQuery,您也应该使用它来发送您的 AJAX 请求:
// This code supports multiple type="file" inputs
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
// Create a formdata object and add the file
var data = new FormData();
// In case you want to upload more than one file
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'your.php?FileInput',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Prevent the file from beeing converted to string
contentType: false, // Set the content file to false prevent JQuery from using 'application/x-www-form-urlencoded; charset=UTF-8' as default type
...
});
我希望这会引导您找到解决方案...
编辑:var files
申报 + files
处理
关于javascript - 表单未提交文件/未定义索引 : FileInput - PHP/AJAX/jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32761805/