【问题标题】:JSON index adds to itself instead of starting by 0 on reloadJSON 索引添加到自身而不是在重新加载时从 0 开始
【发布时间】:2011-06-28 16:41:38
【问题描述】:

我确信这一定有一个简单的解决方案,但我似乎无法正确解决。 当我在 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});
                };

    });

    });
};

【问题讨论】:

  • 什么是 responseText?它在重新加载时如何变化?
  • 显示那个函数和你得到的响应(JSON)怎么样?您发布的代码行没有告诉我们任何信息。
  • 我已经添加了这个功能,希望对你有帮助。
  • 这个函数还是没有多大意义,谁把json传给A2B.mapview的click handler?您的代码格式仍然很糟糕,我试图为您修复它,但您有各种不匹配的括号
  • 您好 Juan,请注意这是一个 appcelerator 项目,正在另一个“视图”中调用 A2B。调用它的方式是这样的 A2B.createView();。关于在我裁剪代码添加到这里时可能出现的括号,我现在重新检查一下。

标签: javascript json function appcelerator


【解决方案1】:

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

this.xmlHttpRequest =  new XmlHttpRequest()

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

【讨论】:

  • 我从来没有听说过 responseTexts 被连接在一起......你说你有?
  • 是的。在我不久前做的一个项目中,我正在创建一个 API 包装器,用于与 WebDVR 网络服务进行通信。在创建我的 API 类/对象的实例时,当需要发出请求时,我将 XmlHttpRequest 对象存储为 this.XmlHttpRequest (在实例化时在 init 函数中创建了它)。在进行第二次调用后(在我的 JUnit 测试中),我看到新的 responseText 添加到之前的调用响应文本中(测试失败)。解决方案是为每个 API 调用创建一个“新鲜”的 XmlHttp 对象;即 var XmlHttpRequest = new {...}.
猜你喜欢
  • 2020-11-21
  • 2012-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
  • 2021-06-12
  • 2023-03-30
  • 1970-01-01
相关资源
最近更新 更多