完成后函数调用php

时间:2018-10-20 15:03:20

标签: javascript php ajax return

我正在尝试使用状态栏制作一个上传器,该状态栏使用ajax制作,因此其形式包括onSubmit=“return false”。如果包含此文件,则加载程序可以正常工作,但不能正确上传文件;如果删除该文件,则加载程序将不工作,因为页面正在加载,但上传成功。

这是我的表格:

  <form enctype="multipart/form-data" action="/upload" method="POST" onSubmit="return false">
    <h5>Requirements:</h5>
    <li>Max. limit 250Mb</li>
    <br />
    <input type="file" id="file1" name="file" required></input>
    <hr></hr>
    <div id="uploading"  style="display:none;"><p id="status"></div>
        <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
   <p id="loaded_n_total"></p>
    <input onclick="showDiv();uploadFile()" class="btn btn-lg btn-primary btn-block" type="submit" value="Upload"></input>
  </form>

这是我的JS:

  <script>
  function _(el) {
  return document.getElementById(el);
}

function uploadFile() {
  var file = _("file1").files[0];
  // alert(file.name+" | "+file.size+" | "+file.type);
  var formdata = new FormData();
  formdata.append("file1", file);
  var ajax = new XMLHttpRequest();
  ajax.upload.addEventListener("progress", progressHandler, false);
  ajax.addEventListener("load", completeHandler, false);
  ajax.addEventListener("error", errorHandler, false);
  ajax.addEventListener("abort", abortHandler, false);
  ajax.open("POST", "upload.php");
  ajax.send(formdata);
}

function progressHandler(event) {
  _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
  var percent = (event.loaded / event.total) * 100;
  _("progressBar").value = Math.round(percent);
  _("status").innerHTML = Math.round(percent) + "% Uploaded...Please wait.";
}

function completeHandler(event) {
$.ajax({
    data: 'file',
    url: 'upload.php',
    method: 'POST',
    success: function(msg) {
        alert(msg);
    }
});
}

function errorHandler(event) {
  _("status").innerHTML = "Upload Failed";
}

function abortHandler(event) {
  _("status").innerHTML = "Upload Aborted";
}
  </script>
  <script>
  function showDiv() {
   document.getElementById('uploading').style.display = "block";
}
  </script>

1 个答案:

答案 0 :(得分:0)

如果要使用Ajax发送文件,则需要使用FormData

var form_data = new FormData();
var file = $(this)[0].files[0];
form_data.append('image', file);
function completeHandler(event) {
    $.ajax({
        data: form_data,
        url: 'upload.php',
        method: 'POST',
        cache: false,
        processData: false,
        contentType: false,
        success: function(msg) {
            alert(msg);
        }
    });
}