AJAX加载器动画未显示

时间:2012-09-03 14:40:30

标签: javascript ajax

我有一个AJAX脚本,它应该在执行后触发加载图像,然后在我从Web服务获得结果后隐藏它,但图像现在显示。

我的代码如下:

    <script type="text/javascript">
        function get_Code_Results() {
            document.getElementById("loader").innerHTML = "<img src=\'loading.gif\' />";
            var url = document.location;
            if (window.XMLHttpRequest) req = new XMLHttpRequest();
            else if (window.ActiveXObject) req = new ActiveXObject("Microsoft.XMLHTTP");
            req.onreadystatechange = processRequest;
    //      req.open("GET", url, true);
    //      req.send(null);
            req.open("POST",url,true);
            req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            req.send("isbns="+document.getElementById("Code").value);
            function processRequest() {
        if (req.readyState == 4 && document.getElementById("1").checked == true) {
            document.getElementById("results").value = "myfirsturl.com" + req.responseText;
        }
        else if (req.readyState == 4 && document.getElementById("2").checked == true) {
            document.getElementById("results").value = "myurl.com" + req.responseText;
        }           
    }
}
    </script>

我有一个位置,我希望显示加载器:

    <div id="loader"><img src="loading.gif" style="display:none;" /></div>

我的代码中哪里有错误?一些建议将不胜感激!

2 个答案:

答案 0 :(得分:1)

  <div id="loader"><img src="loading.gif" style="display:none;" /></div>

您需要更改style="display:none;"。我建议你改为编写以下代码:

<div id="loader" style="display:none;"><img src="loading.gif" /></div>

然后在需要时:

$('#loader').show(); // To show the laoding icon
$('#loader').hide(); // To hide it

答案 1 :(得分:1)

您的功能是嵌套的。我想你假装写下这样的东西:

function get_ISBN_Results() {
            document.getElementById("loader").innerHTML = "<img src=\'loading.gif\' />";
            var url = document.location;
            if (window.XMLHttpRequest) req = new XMLHttpRequest();
            else if (window.ActiveXObject) req = new ActiveXObject("Microsoft.XMLHTTP");
            req.onreadystatechange = processRequest;
    //      req.open("GET", url, true);
    //      req.send(null);
            req.open("POST",url,true);
            req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            req.send("isbns="+document.getElementById("isbns").value);
}
function processRequest() {
        if (req.readyState == 4 && document.getElementById("book").checked == true) {
            document.getElementById("results").value = "myfirsturl.com" + req.responseText;
        }
        else if (req.readyState == 4 && document.getElementById("magazine").checked == true) {
            document.getElementById("results").value = "myurl.com" + req.responseText;
        }           
 }