使$.getJSON立即与for不同

Make a $.getJSON available immediately difference with for

本文关键字:for 不同 getJSON      更新时间:2023-09-26

编辑:

$.getJSON(url, function (data) {
var x = 0;
var places = [];
$.each(data.lugar, function (i, user) {
    places[x] = {
        canEdit: false,
        lat: user.latt,
        lng: user.lng,
        name: "Somewhere "+x
    };
    alert(isNumber(places[x].lng));
    x++;
}).promise().done(function () {
    $(document).ready(function() {
        runExample5();
    });
});
});

因此,我试图用类似的javascript填充地图

{ showOnLoad: places ....

它用这样的for循环完成了任务(它确实显示了标记(this WORKS

 var places = [];
  for(var x= 0; x<10; x++){
  places[x] = {
    canEdit: false,
    lat: 53.79+x,
    lng:-1.5426760000000286+x,
    name: "Somewhere "+x
}
}

但是,当我试图用我在JSON/PHP上从另一个页面收到的信息填充它时,它不起作用,也不使用标记填充。。。

 var places = [];
$.getJSON(url, function (data) {
var x = 0;
$.each(data.lugar, function (i, user) {
    places[x] = {
        canEdit: false,
        lat: user.latt,
        lng: user.lng,
        name: "Somewhere "+x
    };
    x++;
}).promise().done(function () {
});
});

function runExample5(a) {
 $("#search-for-places").mapsed({
    showOnLoad: places,
    allowGeo: true, 
    disablePoi: true

});                                 
 }

 $(document).ready(function() {
runExample5();
 });

除非我调用另一个函数,然后它自动显示标记,否则我不会得到填充,但当地图第一次加载时,我似乎一开始就无法得到它,但当我使用FOR循环时,我得到了它。

为了完成,这里有正确的解决方案:

$.getJSON(url).then(function (data) {
    // instead of map(), you could also use that tedious `each` loop
    // it would work the same
    return $.map(data.lugar, function (i, user) {
        return {
            canEdit: false,
            lat: user.latt,
            lng: user.lng,
            name: "Somewhere "+x
        }
    });
}).done(function (places) {
    $(document).ready(function() {
        // if you wanted to call a runExample5 function, make `places` a parameter
        $("#search-for-places").mapsed({
            showOnLoad: places,
            allowGeo: true, 
            disablePoi: true
        });
    });
});