我认为你的主要问题是你的数据嵌套在一个名为data
所以你需要额外的参考才能进入其中。当您像这样设置响应格式时,也可以更容易地看到您所得到的内容,这样您就可以更清楚地看到嵌套的对象和数组:
({ "data": {
"current_condition": [
{
"cloudcover": "50",
"humidity": "44",
"observation_time": "12:10 AM",
"precipMM": "0.0",
"pressure": "1013",
"temp_C": "-2",
"temp_F": "29",
"visibility": "16",
"weatherCode": "116",
"weatherDesc": [
{"value": "Partly Cloudy" }
],
"weatherIconUrl": [
{"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0004_black_low_cloud.png" }
],
"winddir16Point": "W",
"winddirDegree": "280",
"windspeedKmph": "24",
"windspeedMiles": "15"
}
],
"request": [
{"query": "Rochester, United States Of America", "type": "City" }
],
"weather": [
{
"date": "2012-02-25",
"precipMM": "2.2",
"tempMaxC": "-1",
"tempMaxF": "31",
"tempMinC": "-5",
"tempMinF": "24",
"weatherCode": "116",
"weatherDesc": [
{"value": "Partly Cloudy" }
],
"weatherIconUrl": [
{"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0002_sunny_intervals.png" }
],
"winddir16Point": "W",
"winddirDegree": "281",
"winddirection": "W",
"windspeedKmph": "54",
"windspeedMiles": "34"
}
]
}
})
也就是说,如果你想得到当前的情况temp_C
,它会是这样的(注意我更改了匿名函数的参数名称以使代码不那么混乱):
$.getJSON( urlFromMyAPI, function(response){
var temp = response.data.current_condition[0].temp_C;
});
如果您希望温度为数字,您可能需要这样做:
$.getJSON( urlFromMyAPI, function(response){
var temp = parseInt(response.data.current_condition[0].temp_C, 10);
});