JSON索引添加到自身,而不是在重新加载时从0开始

JSON index adds to itself instead of starting by 0 on reload

本文关键字:加载 新加载 开始 添加 索引 JSON      更新时间:2023-09-26

我确信这一定有一个简单的解决方案,但我似乎做不好。当我用javascript重新加载从外部JSON读取数据的函数时,如下所示:

var json = JSON.parse(this.responseText);

json.index第一次使用从0开始的索引时工作得很好,但当我重新加载函数(或再次调用函数)时,索引是(0+json.length),这对我来说是个问题,因为我需要索引才能在另一个窗口中获得正确的数据。关于如何在每次运行函数时让json以index=0开头,有什么线索吗?

非常感谢!

更新:这是我正在重新调用的函数。为了简洁起见,对代码进行了裁剪。同样值得注意的是,这是一个Appcelerator项目。

A2B.createView = function(tipo) {
    var xhr = Ti.Network.createHTTPClient();
    xhr.open("GET","http://localhost.com");
    xhr.onload = function() {
        var json = JSON.parse(this.responseText);
        if (!json) { 
            Titanium.API.info('Error - Null return!'); 
            return;
        }
         var myAnnotations = new Array();
         var json = json.all;
         var pos;

        if (tipo==1){
        for( pos=0; pos < json.length; pos++){
          // this adds some markers to a map
          myAnnotations.push(dbMarker);
        }
        }
        else {
            for( pos=0; pos < json.length; pos++){
         myAnnotations.push(dbMarker);
        }           
        }

        A2B.mapview.annotations = myAnnotations;

    };
    xhr.send();

    A2B.win.add(A2B.mapview);
    // map view click event listener
    A2B.mapview.addEventListener('click', function(json) {
        if (json.clicksource == 'rightButton') {
                var w2 = Titanium.UI.createWindow({
                    title:'XXX', 
                    url:'eachevent.js', 
                    backgroundColor:'#f8f8f8'
});
                w2.stringProp1 = ''+json.index+'';
//the value of json.index is the one that it keeps adding to itself when I call the function
                w2.myFunc = function()
                {
                    return 'myFunc was called';
                };
                w2.open({modal:true});
                };
    });
    });
};

是否每次都重用/缓存相同的XmlHttpRequest对象?即

this.xmlHttpRequest =  new XmlHttpRequest()

如果是这样的话,可能是多个responseText连接在一起的问题,从而创建一个越来越长的解析后的json变量。你能给我们看看代码吗?