1

我正在使用一些本地 json 文件,但我在加载速度方面遇到了一些问题。我的服务器只是一个用 python 制作的小型网络服务器,我通常用它来尝试我的 javascript 代码。我的脚本仅适用于 Firefox,我必须延迟 60000 毫秒(或使用 firebug)。脚本是:

function geisson()
{
var iabile = new XMLHttpRequest();

iabile.open("GET", "longanocard.json", true);
iabile.send(null);


PerdiTempo(60000);

var objectjson = {};
var arrayCards= []; //creazione dell'array che conterrà le cards


objectson = JSON.parse(iabile.responseText);

arrayCards = objectson.cards;
//alert(arrayCards[0].__guid__.toSource());


var qwerty = arrayCards[0].__guid__;

var mela = "http://www.airpim.com/png/public/card/" + qwerty + "?width=292";    


document.location = mela;
//windows.location.href= mela;
}

PerdiTempo 是我用于延迟的函数:

function PerdiTempo(ms)
{
ms += new Date().getTime();
while (new Date() < ms){}
}

如何加快文件 longanocard.json 的加载速度?为什么延迟不适用于其他浏览器?

4

1 回答 1

2

你真的应该避免以这种方式等待异步响应(你怎么知道 JSON 解析延迟了多少秒?),而是使用onreadystatechange你的请求的事件

function geisson() {

    var iabile = new XMLHttpRequest();

    iabile.onreadystatechange = function(){
        if(iabile.readyState === 4 && iabile.status === 200) {
            var objectjson = {};
            var arrayCards= []; //creazione dell'array che conterrà le cards
            objectson = JSON.parse(iabile.responseText);

            ...
            /* codice restante qui */

        }
    }
    iabile.open("GET", "longanocard.json", true);
    iabile.send(null);

}
于 2012-06-22T13:28:56.063 回答