未捕获的类型错误:使用 $.param() 序列化传单数据时无法读取未定义的属性"lat"



我想序言:我对javascript非常新。我正在尝试将用户位置发布并与传单和AJAX调用映射。在我的活动中,处理程序stateUpdater.onLocationFound日志语句打印出正确的用户坐标和映射界限,但是在尝试用$.param()序列化这些值时,我会得到Uncaught TypeError: Cannot read property 'lat' of undefined。我正在使用传单v0.7.2和jQuery 1.11.0。

var map;
$(document).ready(function() {
    map = new L.map('map').setView([41.52, -71.09], 11);
    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 18
    }).addTo(map);
    map.on('locationfound', stateUpdater.onLocationFound);
    stateUpdater.poll();
});
var stateUpdater = {
    errorSleepTime: 10000,
    poll: function() {
        map.locate({setView: true, maxZoom: 18});
    },
    onLocationFound: function(e) {
        //This log statement produces the correct output
        console.log(e.latlng.toString());
        var bounds = map.getBounds();
        //As does this one
        console.log(bounds.toBBoxString())
        var args = {
            "map_ne": bounds.getNorthEast(),
            "map_sw": bounds.getSouthWest(),
            "user_coords": e.latLng
        };
        //Uncaught TypeError thrown here
        $.ajax({url: "/a/state/updates", type: "POST", dataType: "text",
            data: $.param(args),
            success: stateUpdater.onSuccess,
            error: stateUpdater.onError});
    },
    onSuccess: function(response) {
        console.log(response);
        stateUpdater.errorSleepTime = 10000;
        window.setTimeout(stateUpdater.poll, 10000);
    },
    onError: function(response) {
        stateUpdater.errorSleepTime *= 2;
        console.log("Poll error; sleeping for", stateUpdater.errorSleepTime, "ms");
        window.setTimeout(stateUpdater.poll, stateUpdater.errorSleepTime);
    },
};

我对可能导致的是什么,所以我非常感谢您的帮助。

看起来像 bands.getnortheast() bands.gets.getsouthwest() and and e.latlng 除了 lat,LNG 坐标之外,还包含一些功能的返回对象,例如 quare() and toString() ,可以预防 $。param()通过正确执行数据的序列化,这会导致您的错误,这是一种仅从这些对象中获得所需的东西的好方法:

    var ll= $.extend({},{lat:e.latlng.lat, lng:e.latlng.lng}), 
        neBounds = bounds.getNorthEast(), 
        neBoundsLl = $.extend({},{lat:neBounds.lat, lng:neBounds.lng}),
        swBounds = bounds.getSouthWest(), 
        swBoundsLl = $.extend({},{lat:swBounds.lat, lng:swBounds.lng}),
        args = {
        "map_ne": neBoundsLl,
        "map_sw": swBoundsLl,
        "user_coords": ll
    };

我测试了此代码,它对我有用,错误消失了,AJAX请求已成功发送。

最新更新