【发布时间】:2015-09-24 22:44:08
【问题描述】:
我正在尝试使用 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.";
}
我知道问题在于我的表单没有提交所选文件,因为这通常是引发“未定义索引”错误的原因。但我不明白为什么。
【问题讨论】:
-
展示浏览文件功能
-
似乎有点脱节。您仍在使用内联 JavaScript,这会混淆对我而言的流程。其他人可能会看到它。 AJAX 的
dataType是错误的,您可以在那里放置的内容有严格的限制(xml、json、脚本或 html)。仅使用 AJAX 执行文件上传通常是禁止的,但如果您使用的是 HTML5,则有一些方法可以解决。 -
@AkhileshSingh - browseFile 函数唯一做的就是调用文件输入标签(我把它隐藏了,因为它很难看)。 @JayBlanchard - 上传没有发生在 AJAX 中,它发生在调用提交输入标签的
submitForm函数中。但是你能进一步解释为什么内联 javascript 会让人困惑吗?它所做的只是调用 .js 文件中的一个函数 -
我已经更新了我的 AJAX 函数
标签: javascript php jquery ajax forms