使用jQuery上传文件时显示loading.gif

时间:2016-03-05 08:46:40

标签: javascript jquery html

如何使用jQuery上传文件时显示loading.gif

<input type="file" class="form-control" name="profilepic" id="profilepic" accept="image/*" required >
<div id="loader_img"></div>

<button type="submit" name="submit" id="submit" class="btn btn-primary"><span class="glyphicon glyphicon-check"></span> Save</button>

当我点击save按钮时,必须在加载文件时显示loading.gif

这是我的jQuery:

<script>
$(function() {
  $('form[name="chngimg"]').find('input,select,textarea').not('[type=submit]').jqBootstrapValidation({
    submitSuccess: function ($form, event) {

      $.ajax({
            type: "POST",
            url: "propicchng.php",
            data: $('form').serialize(),
            success: function(msg){
             $('#loader_img').show();

                          // just to confirm ajax submission
          $("#imgchng").modal('hide');
                    alert(msg);
                    $( '#chngimg-form' ).each(function(){
                     this.reset();
                     });},
            error: function(){
                alert("failure");
                }
                });
      event.preventDefault();
    }
  });
});
</script>

1 个答案:

答案 0 :(得分:3)

@Mehran Torki 所说的是你需要首先将加载器放在请求之前显示 - 然后在成功回调中隐藏它。这就是您的代码应该如何显示加载器 - 请注意评论!

$(function() {
  $('form[name="chngimg"]').find('input,select,textarea').not('[type=submit]').jqBootstrapValidation({
    submitSuccess: function ($form, event) {
      //here - showing loader to the user
      $('#loader_img').show();
      $.ajax({
        type: "POST",
        url: "propicchng.php",
        data: $('form').serialize(),
        success: function(msg){
          //here - hiding when request is done
          $('#loader_img').hide();
          // just to confirm ajax submission
          $("#imgchng").modal('hide');
          alert(msg);
          $( '#chngimg-form' ).each(function(){
            this.reset();
          });},
        error: function(){
          alert("failure");
        }
      });
      event.preventDefault();
    }
  });
});