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

2024-04-04

我想先说一下:我对 JavaScript 很陌生。我正在尝试使用 Leaflet 和 AJAX 调用来发布用户位置和地图边界。在我的事件处理程序中stateUpdater.onLocationFound日志语句打印出正确的用户坐标和地图边界,但是我得到Uncaught TypeError: Cannot read property 'lat' of undefined当尝试序列化这些值时$.param()。我正在使用 Leaflet 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);
    },
};

我对可能导致此问题的原因不再有任何预感,因此我将非常感谢您的帮助。


这好像是边界.getNorthEast(), 边界.getSouthWest() and e.latlng返回包含一些函数的对象lat,lng坐标,比如equal() 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请求发送成功。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐