一切正常,但 Ajax

Everything works but the Ajax

正在调用 openweather API。当我在浏览器中输入 URL 时,我可以看到 JSON 对象。然而,我下面的 ajax 不允许任何内容出现在我的 HTML 中。即使我想要 document.write 整个 json 对象,我也做不到。我可以输出纬度和经度,这样地理定位就可以正常工作了。不确定这段代码有什么问题。

这是HTML:

<body>
  <div class="container">
  <div class="col-lg-12 header">
    <h1>My Location</h1>
  </div>
    <div class="row text-center box">
      <div class="col-lg-12" id="data">Lat Long</div>
    </div>
  </div>
</body>

这是 JS:

$(document).ready(function() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(main); 
  }
});
function main(position){
  var lat = position.coords.latitude;
  var long = position.coords.longitude;
  var api = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat      + "&lon=" + long + "&appid=[redacted key]";
  $.ajax({
    dataType: 'json',
    url: api,
    success: function(data) {
        city = data.name;
        $("#data").html(city);
    }
  });
}

问题不在您的 ajax 电话中。

您的代码似乎在硬编码坐标下工作得很好,并且在 Chrome 以外的所有其他浏览器上也能以其当前形式工作。

如果您想在较新版本的 Google Chrome 上使用地理定位,您的主机必须是安全主机 (HTTPS)。

Chrome 警告:

getCurrentPosition() and watchPosition() are deprecated on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins for more details.

尝试 $.getJson 而不是 $.ajax $.getJSON( { dataType: 'jsonp', url: api, success: function(data) { city = data.name; $("#data").html(city); }

在 HTML 中,确保添加 jquery:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script> <script src="a.js"></script> // 不管你的 js 文件是什么名字

在不修改您的代码的情况下,该页面要求访问我的位置,然后显示我当前所在的城市。我不确定它应该输出什么。您期望输出是什么?