如何在 AJAX 调用中遍历 latitude/longitude 对数组

How to loop through array of latitude/longitude pairs in AJAX call

我是 PHP/AJAX 的新手,需要一些帮助...我有一张传单地图,正在尝试链接两个 AJAX 调用 - 第一个 AJAX 使用数据来自 select 值(国家 ISO 代码)。

然后我使用地名 API 找到该特定国家/地区人口最多的城市。我想使用这 10 个城市中每个城市的结果 latitude/longitude(目前成对存储在 $latLng 中)作为参数来调用其他一些 APIs(例如开放天气)并将此信息动态添加到当用户单击该特定传单标记时的模态。目前,我已将变量 $latLng 分配给第二次 AJAX 调用中的数据,但这不起作用,因为我无法将数组传递到 cURL 例程中。

下面是 $latLng 当前在控制台中显示的示例(对于 AU(澳大利亚))- 每对都作为标记出现在传单地图上指定坐标处:

(2) [-35.2834624726481, 149.128074645996]
(2) [-33.8678499639382, 151.207323074341]
(2) [-37.8139965641595, 144.963322877884]
(2) [-31.95224, 115.861397]
(2) [-34.928661, 138.598633]
(2) [-32.92953, 151.7801]
(2) [-42.87936056387943, 147.32940673828125]
(2) [-19.26639, 146.805695]
(2) [-16.92366, 145.76613]
(2) [-12.46113366159021, 130.84184646606445]

有没有一种方法可以遍历这些对,以便每个对都可以在第二个 AJAX 调用中使用,具体取决于单击的是哪对?例如,如果我单击位置 [-12.46113366159021, 130.84184646606445] 处的标记,那么该城市的天气数据将以模式显示?

在第二次 AJAX 调用的 PHP 文件中:

$url='https://restcountries.eu/rest/v2/alpha/' . $_REQUEST['latlng']

我收到错误消息 Undefined array key "latlng"

['latlng'] 是两个值的数组。 latlng[0] 包含纬度,latlng[1] 包含经度。

当前代码如下 - 如有任何帮助,我们将不胜感激。谢谢!

JS:

$("select").on('change', () => {
        $.ajax({
            url: "libs/php/getInfo.php",
            type: 'POST',
            dataType: 'json',
            data: {
                code: $('#select').val()
            },
            success: function(result) {

                console.log(result);

                if (result.status.name == "ok") {

                    var cities = result['data']['cities']['geonames'];

                    var citiesArray = [];

                    for (i=0; i<cities.length; i++) {
                        if (cities[i].countrycode == result['data']['restCountries']['alpha2Code']) {
                            citiesArray.push(cities[i]);
                        }
                    }

                    citiesArray.length = 10;
                    citiesArray.forEach(city => {
                        
                        $latLng = [city.lat, city.lng];
                        $cityMarker = L.marker($latLng)
                        .addTo($layers)
                        .bindPopup('Name: ' + city.toponymName)

                        $($cityMarker).on('click', () => {
                            $.ajax({
                                url: "libs/php/getInfoLatLng.php",
                                type: 'POST',
                                dataType: 'json',
                                data: {
                                    latlng: $latLng
                                },
                                success: function(result) {
                    
                                    console.log(result);
                    
                                    if (result.status.name == "ok") {
                    
                                        $('.modal').modal('show');
                                        console.log($latLng);
                                        $('#openWeatherResult').html('weather info goes here');
                                    }
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    console.log(errorThrown);
                                    console.log(textStatus);
                                    console.log(jqXHR);
                                }
                            });
                        });
                        $('.close').on('click', () => {
                            $('.modal').modal('hide');
                        })
                    });

                }

            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
                console.log(textStatus);
                console.log(jqXHR);
        }
    });
});

举一个简单的例子,粗略地基于你上面的代码:

let latLng = ['latitude', 'longitude'];
$.ajax({
    method:'POST',
    url:'myUrl.php',
    data: {latlng:latLng}
}

这将使用数组表示法将 latLng 数组发送到您的 PHP 脚本。发送的内容格式为:

myUrl.php?latlng[]=latitude&latlng[]=longitude 

PHP 将看到一个 latlng 数组作为 $_POST:

的一个元素
array (size=1)
  'latlng' => 
    array (size=2)
      0 => string 'latitude' (length=8)
      1 => string 'longitude' (length=9)

要获得这些值,您可以使用

 echo $_POST['latlng'][0];  // latitude
 echo $_POST['latlng'][1];  // longitude

更进一步,您可以将这些 latitude/longitude 对添加到数组中,并且 POST 即:

$latLng=[['latitudeA', 'longitudeA'],['latitudeB', 'longitudeB']];
$.ajax({
    method:'POST',
    url:'myUrl.php',
    data: {latlng:latLng}
}

所以现在你有两层数组,所以需要两层来访问值:

echo $_POST['latlng'][0][0];  // latitudeA
echo $_POST['latlng'][1][0];  // latitudeB

这很快就会变得繁琐且难以阅读。另一种方法是使用对象数组,并使用 JSON.stringify() 到 POST 它们。

let locationList = [];
citiesArray.forEach(city => {
    locationList.push({lat:city.lat, long:city.long});
});
$.ajax({
   url:'myUrl.php',
   method:'POST',
   data: {
      locationList:JSON.stringify(locationList)
   }
})   

在 PHP 中,您将 JSON 字符串解码为一个对象数组:

<?php
    if (isset($_POST['locationList']){
        $locationList = json_decode($_POST['locationList']);
        foreach($locationList as $location){
            // do something with the data
            echo $location->lat;       
            echo $location->long;
           
       }
    } else {
         // handle a request with no data
    }

您必须弄清楚如何将其合并到您的代码中。