在执行ajax时显示加载图像

时间:2016-08-23 15:29:50

标签: jquery ajax

我正在尝试将ajax加载图像添加到div容器中,同时执行ajax请求。

我的Jquery代码如下所示:

<script type="text/javascript">
    $(document).ready(function(){
        $("#store, #gender, #username").change(function () {
            var store = $("#store").val();
            var gender = $("#gender").val();
            var receiver = $("#username").val();

            $.ajax({
                type: "POST",
                data: {
                    "store" : store,
                    "gender" : gender,
                    "receiver" : receiver
                },
                url: "handling/ajax/store_items_ajax.php",
                success: function(data){
                    $("#result").html(data);
                }
            });
        });
    });
</script>

如何将加载图像添加到以下html div:

<div id="result" class="col-md-12"></div>

有谁知道这个?

1 个答案:

答案 0 :(得分:4)

Logic

- Create progress div element
<div id="progress">
    <img style="width:100%" src="/images/spinner.gif"/>
</div>

- By default hide this progress div
- Show when passing ajax request
- Hide when you get ajax response

Script

<script type="text/javascript">

    $(document).ready(function() {

      $("#store, #gender, #username").change(function () {
        var store = $("#store").val();
        var gender = $("#gender").val();
        var receiver = $("#username").val();

        $('#progress').show(); //show progress bar

        $.ajax({
            type: "POST",
            data: {
              "store" : store,
              "gender" : gender,
              "receiver" : receiver
            },
            url: "handling/ajax/store_items_ajax.php",
            success: function(data){
              $('#progress').hide(); //hide progress bar
              $("#result").html(data);
            }
        });
      });

    });

</script>