weixin_33681778 2016-04-14 21:55 采纳率: 0%
浏览 67

来自API的JSON响应

I am trying to pull in weather data in JSON form using an API. It is successfully returning data from the API, however when trying to access the properties of the object I get the following:

Uncaught SyntaxError: Unexpected token :

I know the response is coming back because I can see it returns this

{"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}

Here is the code I am using:

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);
}
  • 写回答

1条回答 默认 最新

  • weixin_33720186 2016-04-14 22:03
    关注

    Just request the data normally. Don't use jsonp. jQuery will handle the conversion for you.

    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>

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)