【发布时间】:2015-06-19 17:25:30
【问题描述】:
尝试学习如何使用新的 AJAX 文件上传,而不是使用 iframe 或旧的 PHP 文件上传。我了解 XHR 请求的工作原理,并且长期以来一直使用 jQuery 的 $.post。但是我拿不到这个。
原因:当我发布数据(我要上传的文件)时,我只能通过$_POST 全局访问它,而不是必需的$_FILES 全局访问。这是我的一些代码非常快:
<input type="file" id="file"/>
<input type="submit" id="submit" value="Upload" />
$("#file").on("change",function () {
var file = this.files[0];
}
$("#submit").click(function () {
var formData = new FormData();
formData.append('file',file);
$.ajax({
url: '<?php echo BASE_URL; ?>ajax/upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
在 PHP 脚本中,当我 var_dump $_POST 时,我正在获取文件,但当我 var_dump $_FILES 时,那里什么都没有。我找到了这些资源,但它们似乎对我不起作用:
【问题讨论】:
-
我已编辑标题以描述您的确切问题。使用一个非常具体的标题有助于引起对问题的更多关注。我改进了代码块的格式,列出了资源(两者之间的
/不是很清楚)以及大写的缩写。
标签: php jquery ajax file-upload superglobals