我希望我的代碼能夠獲取 JSON 并讀取倫敦的溫度值。
任何幫助將不勝感激。
但是我有兩個問題,獲取的資料顯示:[object Object]
- 如何修復它?
- 如何讓它獲取倫敦的溫度值,它是 main 和 temp。
也許是這樣的:
data.["main"].temp
這是倫敦的開爾文溫度,277.21。
我的 JSON:
{
"coord": { "lon": -0.1257, "lat": 51.5085 },
"weather": [{ "id": 800, "main": "Clear", "description": "clear sky", "icon": "01n" }],
"base": "stations",
"main": { "temp": 277.21, "feels_like": 275.36, "temp_min": 274.4, "temp_max": 279.13, "pressure": 1042, "humidity": 93 },
"visibility": 9000,
"wind": { "speed": 2.06, "deg": 230 },
"clouds": { "all": 9 },
"dt": 1642014889,
"sys": { "type": 2, "id": 2019646, "country": "GB", "sunrise": 1641974505, "sunset": 1642004119 },
"timezone": 0,
"id": 2643743,
"name": "London",
"cod": 200
}
我的錯誤代碼:
$.ajax({
url: "https://api.openweathermap.org/data/2.5/weather?q=London&appid=a7a01852c805157a4c8334e87e39c75c",
cache: false,
dataType: "json",
complete: function(data) {
tempLondon = data;
$('#tempLondon').append('The temperature is ' tempLondon );
console.log(tempLondon);
}
});
uj5u.com熱心網友回復:
試試這個
$.ajax({
type: 'GET',
url: "https://api.openweathermap.org/data/2.5/weather?q=London&appid=a7a01852c805157a4c8334e87e39c75c",
dataType: "json",
success: function(data) {
console.log(JSON.stringify(data));
$('#tempLondon').html('The temperature is ' data.main.temp );
},
error: function (error) {
console.log(JSON.stringify(error));
}
});
以后不要把點和括號放在一起。
這是有效的
data.main.temp
//or
data["main"].temp
它無效
data.["main"].temp
uj5u.com熱心網友回復:
當您將物件轉換為字串時,例如嘗試將其直接插入到標記中,它會變成'[object Object]'. 雖然這肯定不直觀,但您必須記住物件可以包含回圈參考,因此可能無法將它們轉換為字串。
但是,您可以改為使用JSON.stringify將物件轉換為 JSON 字串并將其列印到控制臺:
console.log(JSON.stringify(tempLondon, null, '\t'));
因為您的物件首先是從 JSON 字串構造的(這發生在 jQuery 函式的幕后$.ajax),所以它不能包含任何回圈參考,因此從它構造 JSON 字串不會有任何問題。
如果要檢索溫度本身,只需使用點表示法:
console.log(tempLondon.main.temp);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/410724.html
標籤:
