首页 > 解决方案 > Leaflet 中的数据库映射(JSON、AJAX)

问题描述

我从 DeviceNewController 得到这个 JSON

 public function index(Request $request)
{
    $device_new = Device_new::with(['device']);

    return Device_new::all()->toJson();
}

当我在视图刀片中编写 AJAX 时,它会在控制台中显示来自数据库的数据。

<script>
    var newdev = new XMLHttpRequest();
    newdev.open('GET', '/devices_new');
    newdev.onload = function() {
        console.log(newdev.responseText);
    };
    newdev.send();
</script>

但我需要在 Leaflet 脚本中传递它并在地图上写入所有数据(坐标、标记、设备信息)

当我在一个脚本中设置所有内容时,控制台中没有数据,我无法修复它。

var newdev = new XMLHttpRequest();
    newdev.open('GET', '/devices_new');
    newdev.onload = function() {
        var coordinates = newdev.responseText;

    for (var i=0; i < coordinates.length; i++) {
        if(coordinates[i].x && coordinates[i].y){
        var marker = L.marker([coordinates[i].x, coordinates[i].y])
        .bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)

        .addTo(map);
        }
    };
    };
    newdev.send();

我是不是在某个地方弄错了,这是正确的吗???

标签: jsonajaxdatabaselaravelleaflet

解决方案


我是这样做的,它的工作原理。

<script>
    $(document).ready(function() {
        $.ajax({
            /* the route pointing to the post function */
            url: '/device_new',
            type: 'GET',
            data: {
                message: $(".getinfo").val()
            },
            dataType: 'json',
            /* remind that 'data' is the response of the AjaxController */
            success: function(data) {
                var coordinates = data;
                for (var i = 0; i < coordinates.length; i++) {
                    if (coordinates[i].x && coordinates[i].y) {
                        var marker = L.marker([coordinates[i].x, coordinates[i].y])
                            .bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)

                            .addTo(map);
                    }
                }

                console.log(data);
            },
            error: function(data) {
                console.log(data);
            }


        });
    });
</script>

推荐阅读