AJAX JSON只加载一次,刷新失败时(仅限IE7和8)

时间:2013-04-17 09:51:33

标签: jquery ajax json internet-explorer-8 internet-explorer-7

我有一个用Ajax加载JSON内容的微型网站,它在IE7和IE8中第一次工作,但是如果我刷新那些浏览器它失败了,我已经检查了fiddler并且我没有收到任何错误。这可能是代码中的错误吗?

var firstBackgroundImage = new Image();
                firstBackgroundImage.src = "img/bg-img.jpg";        
                firstBackgroundImage.onload = function () {
                    $('#loading-image').hide();
                    $(".wrap").fadeIn(300);
                    loadContent();
                };

function loadContent(){ 
    $.ajax({
        url: "json/" + language + "/content.json",
        data: "nocache=" + Math.random(),
        type: "GET",
        cache : false,
        contentType: "application/json",
        dataType: "json",
        success: function(source){
            data = source;
            showStartpage(data);
            showInfo(data);
        },
        error: function(data){
            alert("Failed to load content");
        }
    }); 

}

警告“无法加载内容”也不会显示我刚刚显示的加载图像,可能存在的任何可能的错误?有没有人遇到同样的问题?

谢谢!

1 个答案:

答案 0 :(得分:2)

它首次运行是因为Internet Explorer没有从缓存加载图像,因此load事件会在firstBackgroundImage.onload = ...行之后触发以设置事件处理程序。但是,在后续页面加载时,它使用的是图像的缓存版本,因此load事件在为其设置事件处理程序之前就会触发。

只需更改这两行的顺序即可。设置load事件处理程序,然后设置图像的src属性:

var firstBackgroundImage = new Image();
firstBackgroundImage.onload = function () {
    $('#loading-image').hide();
    $(".wrap").fadeIn(300);
    loadContent();
};
firstBackgroundImage.src = "img/bg-img.jpg";