-2

我从 jquery ajax 调用中获取值,但无法保存在全局变量中,我想在另一个函数中使用该值。我想在初始化函数中分配dustValue。

javascript代码

var dustValue;
$.ajax({
    type: "GET",
    url: "http://my url",
    dataType: "json",
    success: function (data) {
        dustValue = data.sensorsdata.PHValue;
    }
});
var myCenter = new google.maps.LatLng(22.8046, 86.2029);
function initialize() {
    var mapProp = {
        center: myCenter,
        zoom: 17,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
    var value = dustValue;//78.55
    var dustbinstatus = '';

    if (value < 50) {
        dustbinstatus = 'img/dustbinempty.png';
    } else if (value > 50 && value < 90) {
        dustbinstatus = 'img/dustbinfull.png';
    } else if (value > 90) {
        dustbinstatus = '3.jpg';
    }

    var marker = new google.maps.Marker({
        position: myCenter,
        icon: v_icon
    });
        marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);

身体

 <div id="googleMap" style="width:1580px;height:780px;"></div>
4

1 回答 1

0

ajax 调用是异步的,所以你可以像下面那样做。我的意思是在成功函数中移动你的 google.maps.event 行

var dustValue;
$.ajax({
    type: "GET",
    url: "http://my url",
    dataType: "json",
    success: function (data) {
        dustValue = data.sensorsdata.PHValue;
        google.maps.event.addDomListener(window, 'load', initialize);
    }
});
var myCenter = new google.maps.LatLng(22.8046, 86.2029);
function initialize() {
    var mapProp = {
        center: myCenter,
        zoom: 17,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
    var value = dustValue;//78.55
    var dustbinstatus = '';

    if (value < 50) {
        dustbinstatus = 'img/dustbinempty.png';
    } else if (value > 50 && value < 90) {
        dustbinstatus = 'img/dustbinfull.png';
    } else if (value > 90) {
        dustbinstatus = '3.jpg';
    }

    var marker = new google.maps.Marker({
        position: myCenter,
        icon: v_icon
    });
        marker.setMap(map);
}

或者你可以使用 when 函数

$.when(ajaxfunction()).done(your logic);
于 2016-08-30T08:41:09.120 回答