代码不显示来自json页面的数据

时间:2016-10-31 00:34:16

标签: javascript jquery arrays ajax

我正在尝试将json页面中的数据显示到我的页面,但数据只显示在[object Object], [object Object], [object Object]

根据我的猜测,我抓住的数据是那些数组中的那些对象,但我没有正确编写代码来显示内容?我尝试了JSON.stringify()和JSON.parse(),仍然没有成功。

以下是json的链接:https://data.nasa.gov/resource/2vr3-k9wn.json

这是代码:
编辑:现在我的代码根本不工作。尔加

function Comet() {
    url = 'https://data.nasa.gov/resource/2vr3-k9wn.json'
    var cometRequest = new XMLHttpRequest();
    cometRequest.onreadystatechange = function() {
        if (cometRequest.readyState === 4 && cometRequest.status === 200) {
            var response = cometRequest.responseText,
                parsedComet = JSON.parse(response);
            for (line in parsedComet) {
                //console.log(line);
                for (i=0; i<line.length; i++) {
                    console.log(parsedComet[line][i]);
                } 
            }
    };
    }
    cometRequest.open("GET", url, true);
    cometRequest.send(null);
}

2 个答案:

答案 0 :(得分:2)

我不确定您要提取哪些数据,但您已经拥有parsedComet[line],您无需在其中添加i

每个parsedComet[line]都是一个Object(就像这个一样):

{  
   "designation":"419880 (2011 AH37)",
   "discovery_date":"2011-01-07T00:00:00.000",
   "h_mag":"19.7",
   "i_deg":"9.65",
   "moid_au":"0.035",
   "orbit_class":"Apollo",
   "period_yr":"4.06",
   "pha":"Y",
   "q_au_1":"0.84",
   "q_au_2":"4.26"
}

因此,如果您想获得orbit_class的值,例如您可以使用:

console.log(parsedComet[line]['orbit_class']);

function Comet() {
    url = 'https://data.nasa.gov/resource/2vr3-k9wn.json'
    var cometRequest = new XMLHttpRequest();
    cometRequest.onreadystatechange = function() {
        if (cometRequest.readyState === 4 && cometRequest.status === 200) {
          debugger;
            var response = cometRequest.responseText,
                parsedComet = JSON.parse(response);
            for (line in parsedComet) {
              //console.log(line);
              console.log(parsedComet[line]);
            }
    };
    }
    cometRequest.open("GET", url, true);
    cometRequest.send(null);
}
Comet();

答案 1 :(得分:1)

您需要与外部交换内部for循环。第一个循环遍历数组对象,另一个循环遍历对象key&amp;值。

function Comet() {
    url = 'https://data.nasa.gov/resource/2vr3-k9wn.json'
    var cometRequest = new XMLHttpRequest();
    cometRequest.onreadystatechange = function() {
        if (cometRequest.readyState === 4 && cometRequest.status === 200) {
            var response = cometRequest.responseText,
                parsedComet = JSON.parse(response);
            for (i=0; i<parsedComet.length; i++) {
            for (line in parsedComet[i]) {
                    console.log(parsedComet[i][line]);
                    //419880 (2011 AH37)
                    //2011-01-07T00:00:00.000
                    //etc....
                } 
            }
    };
    }
    cometRequest.open("GET", url, true);
    cometRequest.send(null);
}