如何将从地理位置获得的城市与数据库中存储的城市进行比较,如果城市存在,则通过 ajax 请求传递 id



我的脚本是

<script type="text/javascript">
   search = new Vue({
     el: '#offers',
     data: {
        data: [],
        authType: '{{uid}}',
        key : '1',
        with_ : 'district',
    },
mounted() { 
 var self = this; 
    navigator.geolocation.getCurrentPosition( success, error );
    data = {};
    data['auth-token'] = this.authType;
    data['key'] = this.key;
    data['with_'] = this.with_;
            function success( position ) {/* geolocation success callback */
                var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
                $.getJSON( GEOCODING ).done( function( location ) {
                    $('#country').html(location.results[0].address_components[5].long_name);
                    $('#state').html(location.results[0].address_components[4].long_name);
                    $('#city').html(location.results[0].address_components[2].long_name);
                    $('#address').html(location.results[0].formatted_address);
                    $('#latitude').html(position.coords.latitude);
                    $('#longitude').html(position.coords.longitude);

    data['city'] = location.results[0].address_components[2].long_name;
 $.ajax({ 
    url: "http://127.0.0.1:8000/alpha/get/", 
    data: data,
    type: "POST",
    dataType: 'json', 
    success: function (e) { 
      if (e.status == 1) { 
      }
    },
  });
  $.ajax({
        url: "http://127.0.0.1:8000/city/",
        method: "GET",
        dataType: "JSON",
        success: function(e) {
            if (e.status == 1) { 
              self.cities = e.data;
            }
          },
     });
   });
   }   
  },
});
</script>

现在有了data['city'],我正在从地理位置经过获得的城市。但是我需要与通过 ajax 请求http://127.0.0.1:8000/city/获得的城市列表进行比较,并将相应的 id 作为 data['city'] 而不是名称发送。我得到获取城市列表的 json 响应

 {"status": true, "data": [{"id": 1, "name": "Palakkad"}, {"id": 2, "name": "kochi"}]}`

我需要将从地理位置获得的城市与上面的列表进行比较,如果城市存在,我需要传递相应的 ID 作为 data['city'] .

请帮助我找到相同的解决方案。我在js方面很弱,这是我的第一个项目。我是初学者。请帮我提供解决方案?

如果我理解正确,给定一个带有城市数据和城市名称的对象,您希望从城市数据中获取匹配的城市 id(如果有匹配(。下面的功能应该适合您。

它会浏览cities.data以查找名称匹配的条目。如果找到,则返回id,否则返回null

const cities = {"status": true, "data": [{"id": 1, "name": "Palakkad"}, {"id": 2, "name": "kochi"}]};
const cityName = 'Palakkad';
function findCity(name) {
  const foundCity = cities.data.find(entry => entry.name === name);
  
  return foundCity ? foundCity.id : null;
}
console.log(findCity(cityName));
console.log(findCity('Houston'));

相关内容

最新更新