结合javascript-AJAX使用swapi

结合javascript-AJAX使用swapi,javascript,ajax,Javascript,Ajax,我试着使用SWAPI,我试着得到这个星球的气候,但我得到的是“未定义的” 基本上,我希望气候是“干旱”而不是“未定义的” 也许“xhttp.response.climate”不是正确的方法。但是怎么做呢 这是我的代码: xhttp.onreadystatechange = function() { if(xhttp.readyState == 4 && xhttp.status == 200) { console.log(JSON.parse(xhttp.response

我试着使用SWAPI,我试着得到这个星球的气候,但我得到的是“未定义的”

基本上,我希望气候是“干旱”而不是“未定义的”

也许“xhttp.response.climate”不是正确的方法。但是怎么做呢

这是我的代码:

xhttp.onreadystatechange = function() {

if(xhttp.readyState == 4 && xhttp.status == 200) {
   console.log(JSON.parse(xhttp.response));
   document.write('The climate of the planet is: ' + 
   '<strong>' + xhttp.response.climate + '</strong>');
 }
}

 xhttp.open("GET", "http://swapi.co/api/planets/1/", true);

 xhttp.send();
这就是我在DEVTOOLS中看到的:

Object {name: "Tatooine", rotation_period: "23", orbital_period: "304", 
diameter: "10465", climate: "arid"…}
climate:"arid"
created:"2014-12-09T13:50:49.641000Z"
diameter:"10465"
edited:"2014-12-21T20:48:04.175778Z"
films: Array(5)
gravity:"1 standard"
name: "Tatooine"
orbital_period:"304"
population: "200000"
residents: Array(10)
rotation_period: "23"
surface_water: "1" 
terrain: "desert"
url: "http://swapi.co/api/planets/1/"
__proto__: Object

在这一行中,您将字符串解析为一个对象:

console.log(JSON.parse(xhttp.response));
这将从字符串创建一个新对象,但不会重新分配
xhttp.response
的值

这意味着
xhttp.response.climate
将不起作用,因为
xhttp.response
仍然是一个字符串,因此这将不起作用:

document.write('The climate of the planet is: ' + 
'<strong>' + xhttp.response.climate + '</strong>');
document.write('地球的气候是:'+
“”+xhttp.response.climate+”);
请尝试以下方法:

var data = JSON.parse(xhttp.response);
console.log(data);
document.write('The climate of the planet is: ' + 
'<strong>' + data.climate + '</strong>');
var data=JSON.parse(xhttp.response);
控制台日志(数据);
文件。写('地球的气候是:'+
“”+data.climate+”);

响应包含JSON字符串形式的对象。您正确地记录了以下内容:

console.log(JSON.parse(xhttp.response));
要修复document.write部分,请将其更改为:

document.write('The climate of the planet is: <strong>' + JSON.parse(xhttp.response).climate + '</strong>');
document.write('The climate of the planet is: <strong>' + JSON.parse(xhttp.response).climate + '</strong>');
var planet = JSON.parse(xhttp.response);
console.log(planet.climate);