从javascript变量中检索和加载json

时间:2012-01-20 19:12:32

标签: javascript json cordova

我的问题非常奇怪。我正在使用phonegap。

我有一个名为“krijgSpellen”的功能。我在“设备就绪”时调用该函数,如下所示:

// Wait for PhoneGap to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // PhoneGap is ready
    //
    function onDeviceReady() {
        readFile();

        var options = { frequency: 3000 };
        watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);

        krijgSpellen(); <--



    }

但是当我这样做时,这是奇怪的部分:

function krijgSpellen(){


            $.getJSON("gegevens.txt",function(result){

// Get all the games
$.each(result.games, function(){
    $(".gamelijst").append("<li><a href='' id=" + this.id + " data-theme='a'>"+ this.game + "</a></li>");


                });

            $(".gamelijst, $.mobile.activePage").listview('refresh');


                      });   
};

这有效,但当我这样做时:

function krijgSpellen(){


        $.each(jsonopgehaald.games, function(){
               $(".gamelijst").append("<li><a href='' id=" + this.id + " data-theme='a'>" + this.name + "</a></li>");
               });

        $(".gamelijst, $.mobile.activePage").listview('refresh');

    };

它不起作用,我在超链接上有相同的代码,当我点击超链接它确实有效。而且我真的需要这样做的方法。

顺便说一下

jsonopgehaald = {"games":[{"id":"2","name":"bartje","photo":"photo2.png","description":"kimpe","length":"is","totalDownloads":"0","totalFinished":"0","locations":[{"id":"3","name":"loc21","photo":"loc21.jpg","description":"loc21","FK_Game_id":"2","lat":"51.0000","long":"4.0000","status":"0"},{"id":"5","name":"loc22","photo":"loc22.jog","description":"locatie 22","FK_Game_id":"2","lat":"51.2330","long":"40.2222","status":"1"}]},{"id":"3","name":"aa","photo":"photo3.jPg","description":"aa","length":"aa","totalDownloads":"0","totalFinished":"3","locations":[{"id":"4","name":"loc4","photo":"loc4.jpg","description":"loc4","FK_Game_id":"3","lat":"51.2191","long":"4.4021","status":"0"}]}]}

1 个答案:

答案 0 :(得分:0)

试试这个:

function krijgSpellen(){

    $.each(jsonopgehaald.games, function(index, value){
           $(".gamelijst").append("<li><a href='' id=" + value.id + " data-theme='a'>" + value.name + "</a></li>");
    });

    $(".gamelijst, $.mobile.activePage").listview('refresh');

};

我测试了它并且它有效。已将indexvalue添加到function()。 value是对您当前所在阵列的引用。