在原型中,我可以用下面的代码显示“加载…”图像:

var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, 
onLoading: showLoad, onComplete: showResponse} );

function showLoad () {
    ...
}

在jQuery中,我可以将服务器页面加载到一个元素中:

$('#message').load('index.php?pg=ajaxFlashcard');

但是我如何附加一个加载旋转到这个命令,因为我在原型?


当前回答

JavaScript

$.listen('click', '#captcha', function() {
    $('#captcha-block').html('<div id="loading" style="width: 70px; height: 40px; display: inline-block;" />');
    $.get("/captcha/new", null, function(data) {
        $('#captcha-block').html(data);
    }); 
    return false;
});

CSS

#loading { background: url(/image/loading.gif) no-repeat center; }

其他回答

$('#message').load('index.php?pg=ajaxFlashcard', null, showResponse);
showLoad();

function showResponse() {
    hideLoad();
    ...
}

http://docs.jquery.com/Ajax/load#urldatacallback

最后我对原来的回复做了两处修改。

从jQuery 1.8开始,ajaxStart和ajaxStop只能附加到文档中。这使得仅过滤某些ajax请求变得更加困难。秀…… 切换到ajaxSend和ajaxComplete可以在显示转轮之前检查当前ajax请求。

以下是修改后的代码:

$(document)
    .hide()  // hide it initially
    .ajaxSend(function(event, jqxhr, settings) {
        if (settings.url !== "ajax/request.php") return;
        $(".spinner").show();
    })
    .ajaxComplete(function(event, jqxhr, settings) {
        if (settings.url !== "ajax/request.php") return;
        $(".spinner").hide();
    })

有几种方法。我更喜欢的方法是在元素本身的ajaxStart/Stop事件上附加一个函数。

$('#loadingDiv')
    .hide()  // Hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;

ajaxStart/Stop函数将在任何Ajax调用时触发。

更新:从jQuery 1.8开始,文档声明. ajaxstart /Stop只能被附加到文档中。这将把上面的代码片段转换为:

var $loading = $('#loadingDiv').hide();
$(document)
  .ajaxStart(function () {
    $loading.show();
  })
  .ajaxStop(function () {
    $loading.hide();
  });

如果你正在使用$.ajax(),你可以使用这样的东西:

$.ajax({
  url: "destination url",
  success: sdialog,
  error: edialog,
  // shows the loader element before sending.
  beforeSend: function() {
    $("#imgSpinner1").show();
  },
  // hides the loader after completion of request, whether successfull or failor.             
  complete: function() {
    $("#imgSpinner1").hide();
  },
  type: 'POST',
  dataType: 'json'
});

虽然设置名为“beforeSend”,但从jQuery 1.5开始,无论请求类型如何,都将调用“beforeSend”。例如,如果输入:'GET', .show()函数将被调用。

我的ajax代码看起来是这样的,实际上,我只是注释掉了async: false行,旋转器就出现了。

$.ajax({
        url: "@Url.Action("MyJsonAction", "Home")",
        type: "POST",
        dataType: "json",
        data: {parameter:variable},
        //async: false, 

        error: function () {
        },

        success: function (data) {
          if (Object.keys(data).length > 0) {
          //use data 
          }
          $('#ajaxspinner').hide();
        }
      });

我在ajax代码之前显示了一个函数中的旋转器:

$("#MyDropDownID").change(function () {
        $('#ajaxspinner').show();

对于Html,我使用了一个字体很棒的类:

<i id=“ajaxspinner” class=“fas fa-spinner fa-spin fa-3x fa-fw” style=“display:none”></i>

希望它能帮助到别人。