【问题标题】:JSON response from API来自 API 的 JSON 响应
【发布时间】:2016-08-06 16:35:52
【问题描述】:

我正在尝试使用 API 以 JSON 形式提取天气数据。它成功地从 API 返回数据,但是当尝试访问对象的属性时,我得到以下信息:

Uncaught SyntaxError: Unexpected token :

我知道响应会返回,因为我可以看到它返回了这个

{"coord":{"lon":122,"lat":45},"sys":{"message":0.0024,"country":"CN","sunrise":1460581662,"sunset":1460630193},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"base":"cmc stations","main":{"temp":280.37,"temp_min":280.37,"temp_max":280.37,"pressure":1004.49,"sea_level":1024.21,"grnd_level":1004.49,"humidity":77},"wind":{"speed":6.9,"deg":182.004},"clouds":{"all":92},"rain":{"3h":1.92},"dt":1460668593,"id":2034323,"name":"Tuquan","cod":200}

这是我正在使用的代码:

function displayWeatherAndLocation() {
$.ajax({
    url: "http://api.openweathermap.org/data/2.5/weather/",
    jsonp: "jsonp",
    dataType: "jsonp",
    data: {
        lat: "45",
        lon: "122",
        APPID: "b8d8272fd3bdb1f099b1288ff750d5e2"
    }
})
.done(test)
.fail();
}

function test(response) {
   console.log(response.main.temp);
}

【问题讨论】:

  • 响应是 JSON,而不是 JSONP。
  • 好的,处理我从这个 API 返回的信息的正确方法是什么?我以为您在发出外部 ajax 请求时必须使用 jsonp?我给它一个函数来返回数据,这就是我认为 jsonp 发生的事情?
  • 只有在服务支持的情况下才能这样做。如果他们不做 JSONP,也不支持 CORS,你需要从你服务器上的脚本发出请求。
  • @Barmar 没错,但他们似乎确实支持 CORS,因为他说他正在取回 JSON(他可能正在使用应用 ID 来使 CORS 生效)。
  • @blex 数据总是回来的,CORS 是由浏览器实现的,而不是服务器。如果响应不包含适当的标头,浏览器会丢弃响应并报告错误。但是当你使用 JSONP 时,它不会使用 XMLHttpRequest,它会创建一个指向远程 URL 的<script> 标签。

标签: javascript json ajax api jsonp


【解决方案1】:

正常请求数据即可。不要使用 jsonp。 jQuery 将为您处理转换。

function displayWeatherAndLocation() {
  $.ajax({
    url: "http://api.openweathermap.org/data/2.5/weather/",
    data: {
        lat: "45",
        lon: "122",
        APPID: "b8d8272fd3bdb1f099b1288ff750d5e2"
    }
  })
  .done(test)
  .fail();
}

function test(weatherData) {
   document.querySelector('pre').innerText = weatherData.main.temp;
}

$('button').click(displayWeatherAndLocation);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click Me</button><br />
<pre></pre>

【讨论】:

    猜你喜欢
    • 2019-02-09
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 2012-11-06
    • 2017-06-14
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多