AJAX上传文件不起作用

时间:2016-05-13 15:30:13

标签: javascript php jquery html ajax

我想使用ajax在浏览器上上传文本文件,但我不知道如何做到这一点。文件未上传,var_dump($ files)回显array(0)。

HTML:

<form id="uploadsql" action="upload.js" method="post" enctype="multipart/form-data">
    <input id="uploadFile" type="text" disabled="disabled" placeholder="Choose File" />
    <div  class="fileUpload btn btn-primary">
        <span>Upload</span>
        <input id="uploadBtn" name="file" type="file" class="upload"required />
    </div>

    <div class="fileUpload btn btn-primary">
        <span>Submit</span>
    <input type = "submit" id="uploadBtn" class="upload" /></div>

    </form>
    <h4 id='loading' >Loading...</h4>
    <div id="message"></div>
    <script type="text/javascript">  
            document.getElementById("uploadBtn").onchange = function () {  
                document.getElementById("uploadFile").value = this.value;
            };
    </script>

JS:

$(document).ready(function (e) {
$("#uploadsql").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
$.ajax({
url: "upload.php", // Url to which the request is send
type: "POST",             // Type of request to be send, called as method
cache: false,             // To unable request pages to be cached
success: function(data)   // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
}));


});

PHP:

<?php
set_time_limit(0);
header('content-type: text/html; charset=utf-8');
header("access-control-allow-origin: *");

include 'connect.php';


if(isset($_FILES["uploadBtn"]["type"]))
{
echo 'yes';

} else {
    $files = $_FILES;
    var_dump ($files);
}



?>

我在这里做错了什么? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

通过查看你的ajax电话,你不会包括&#34;数据&#34; attrribute到ajax对象。但我建议你看看这个答案jQuery AJAX file upload PHP