繁体   English   中英

加载ajax时如何显示图像

[英]how to show image when loading ajax

我想在ajax加载页面时显示图像,然后再次隐藏
然后我尝试此代码,但是图像不会首先显示所有同时完成的内容(php页面需要大约3秒钟的加载时间),因此当我从$("img").css("display","none");行中删除注释时$("img").css("display","none"); 图像永不出现
这是完整的代码

$(document).ready( function(){
    $("#al").click(function(){
        $("img").css("display","inline");
        xmlhttp=new XMLHttpRequest();
        xmlhttp.open("GET","ajax load.php",false);
        xmlhttp.send();
        document.getElementById("showhere").innerHTML=xmlhttp.responseText;
//  $("img").css("display","none");
    });
});

使用CSS

#Loading {
    background:url(images/abc.gif) no-repeat center center;
    height: 64px;
    width: 64px;
    position: fixed;
    z-index: 1000;
    left: 50%;
    top: 50%;
    margin: -25px 0 0 -25px;
}

使用HTML

<div id="Loading" class="dvLoading">
</div>

然后在Ajax调用之前显示div,在Ajax调用之后隐藏div

$('.dvLoading').show(); 
$('.dvLoading').hide(); 

只需使用jquery ajax $ .get函数(我认为php文件名是ajax_load.php?):

$(document).ready( function(){
    $("#al").click(function(){
        $("img").css("display","inline");
        $.get("ajax_load.php","",function(data) {
            document.getElementById("showhere").innerHTML = data;
            $("img").css("display","none");
        });
    });
});

由于您已经在使用jQuery,因此请使用.load() ,并在其回调方法中隐藏图像

$(document).ready(function () {
    $("#al").click(function () {
        $("img").css("display", "inline");
        $("#showhere").load("ajaxload.php", function () {
            $("img").css("display", "none");
        });
    });
});

您已经使用了jQuery,因此可以利用标准的ajax工具,该工具需要许多选项,其中包括successerror功能: jQuery AJAX

在这两个函数中,您应该将

$("img").css("display","none");

display:inline在调用上方发送一行以发送ajax请求时。

您应该将显示内联之后的所有内容包装在setTimeout函数中,并延迟2-5 ms:

$(document).ready( function(){
    $("#al").click(function(){
        $("img").css("display","inline");
        setTimeout(function() {
            xmlhttp=new XMLHttpRequest();
            xmlhttp.open("GET","ajax load.php",false);
            xmlhttp.send();
            document.getElementById("showhere").innerHTML=xmlhttp.responseText;
            $("img").css("display","none");
        }, 2);
    });
});

我不确定主要问题是什么,但是我知道使用CSS,有时更改属性的行为就像异步操作。 推测一下,我认为您有一个竞态条件,其中CSS更改与请求竞争,并且最终同时发生。 该hack本质上告诉请求等待几毫秒,这使css更改可以在请求之前添加到异步队列中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM