2016-04-14 323 views
-1

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

未捕获的SyntaxError:意外的标记:

我知道响应回来,因为我可以看到它返回此

{"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); 
} 
+0

即响应是JSON,不JSONP。 – Barmar

+0

好吧,那么处理我从这个API返回的信息的正确方法是什么?我以为你在做外部ajax请求时不得不使用jsonp?我正在给它一个函数来返回数据,这是我认为正在与jsonp? – jbel406

+0

你只能这样做,如果服务支持它。如果他们不执行JSONP,并且他们不支持CORS,则需要从服务器上的脚本发出请求。 – Barmar

回答

2

只是请求数据正常。不要使用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>