Ajax功能中加载图标未显示 - Codeigniter

3
由于某种原因,我的Ajax加载图标没有正常显示和隐藏。以下是处理ajax调用的jQuery代码片段。我可以使用Chrome的开发人员工具看到#loading DIV,问题在于jQuery没有显示DIV(div本身的内联样式设置为display:none)。如果我删除这个内联样式,它会出现在应该出现的位置... 你觉得我漏掉了什么吗?
//website URL grab - Ajax call
$('.loadBTN').on("click", function(){

    var check_url = $('#web_address').val();

    if (!check_url || check_url == 'http://') { // form validation
        //alert('Please enter valid URL');
        // Do nothing
        return false;
    };

    var web_url = {
        url: $('#web_address').val(),
        ajax: '1' // needed for controller, to verify that request is ajax
    };         

    //display ajax loader animation
    $('#loading').show();

    $.ajax({
        url: 'ajax/web_embed',
        type: 'POST',
        data: web_url,
        success: function(msg) {
            $('#ajaxContent').html(msg); // output success in this container
            $('#loading').hide();
        } 
    });        


    return false;
}); 

在页面打开时,如果您尝试 $('#loading').show();,会发生什么?请在浏览器控制台中查看。 - Mike Gleason jr Couturier
不确定你的意思,伙计... - Mike Barwick
2个回答

5
我建议订阅所有ajax开始/停止事件,不论谁负责它:
$("#loading")
    .ajaxStart(function(){ $(this).show(); })
    .ajaxStop(function(){ $(this).hide(); });

当有ajax请求时,加载动画会出现,当没有进行中的ajax请求时,加载动画会隐藏...
请参考: http://api.jquery.com/ajaxStart/

你建议我把这个放在函数的哪里?我尝试过类似的东西,但没有成功。 - Mike Barwick
假设在body标签结束之前,只要具有id“loading”的元素存在,无论何时执行此JavaScript - Mike Gleason jr Couturier
这是我的DIV,如果有任何区别,请忽略内联样式。它将被转移到CSS中。 <div id="#loading" style="display:none; position: absolute;margin: 50px auto;height: 31px;left: 475px;z-index:9999;"><img src="/img/ajax-loader.gif" height="31" width="31"/></div> - Mike Barwick
我很高兴你解决了它! - Mike Gleason jr Couturier
1
对于那些已经反复检查了元素ID但仍然无法使其工作的人,我不得不将ajax事件附加到文档而不是我的加载覆盖层上:$(document).ajaxStart(function(){$("loading").show();}).ajaxStop(function(){$("loading").hide();}。我正在使用jQuery 2.0.3,并在$(document)ready()中附加ajax事件。 - Peter
显示剩余3条评论

2

在我看来,这是一个更加简洁的Ajax请求。它利用了上下文BeforeSend

var scope = $("#container"); // wrap in a container div to use as the context

    $.ajax({
        url: 'ajax/web_embed',
        type: 'POST',
        data: web_url,
        context : scope,
        beforeSend : function(){ // use beforeSend 
            $('#loading').animate({
                'display'   :   'block'
            });
        },
        success: function(msg) {
            $(this).html(msg); // $(this) == context => #container
        } 
    });        

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接