【问题标题】:Code is not displaying JSON data代码不显示 JSON 数据
【发布时间】:2016-11-05 23:12:16
【问题描述】:

大家好,我正在尝试向 JSON 页面发出请求,获取数据,然后将其显示到我的控制台,但它给了我“未定义”。这是为什么呢?

这是代码,然后JSON页面将发布在它下面:

(function Apod() {
    var api_key = 'NNKOjkoul8n1CH1NoUFo',
        url = 'https://api.nasa.gov/planetary/apod' + "?api_key=" + api_key,
        data;
    var apodRequest = new XMLHttpRequest();
    apodRequest.onreadystatechange = function() {
        if (apodRequest.readyState === 4 && apodRequest.status === 200) {
            var response = apodRequest.responseText;
            var parsedAPOD = JSON.parse(response);
            data += parsedAPOD;
            for (i = 0; i < parsedAPOD.length; i++) {
                data += parsedAPOD[i];
                console.log("Parsing lines: <br>" + parsedAPOD[i]);
            }

        }
        apodRequest.open("GET", url, true);
        apodRequest.send(null);
    }
}());

JSON 页面解析:

{
  "date": "2016-11-05",
  "explanation": "Shot in Ultra HD, this stunning video can take you on a tour of the International Space Station. A fisheye lens with sharp focus and extreme depth of field provides an immersive visual experience of life in the orbital outpost. In the 18 minute fly-through, your point of view will float serenely while you watch our fair planet go by 400 kilometers below the seven-windowed Cupola, and explore the interior of the station's habitable nodes and modules from an astronaut's perspective. The modular International Space Station is Earth's largest artificial satellite, about the size of a football field in overall length and width. Its total pressurized volume is approximately equal to that of a Boeing 747 aircraft.",
  "media_type": "video",
  "service_version": "v1",
  "title": "ISS Fisheye Fly-Through",
  "url": "https://www.youtube.com/embed/DhmdyQdu96M?rel=0"
}

【问题讨论】:

  • 究竟是什么显示未定义?响应是一个对象,而不是一个数组,所以它没有长度。循环根本不应该运行。
  • parsedAPOD 是一个数组吗?所以请改用for in
  • @MamdouhFreelancer do not use for...in
  • 由于您的缩进,很难判断,但 apodRequest.open(...)onreadystatechange 处理程序中,因此永远不会被执行
  • xhr 响应上方的@vlaz 是一个对象,而不是一个数组。

标签: javascript json ajax parsing httprequest


【解决方案1】:

您的代码中有一些错误。

首先,它的大体结构应该是这样的

(function Apod() {
    var api_key = 'NNKOjkoul8n1CH1NoUFo',
        url = 'https://api.nasa.gov/planetary/apod' + "?api_key=" + api_key,
        data;
    var apodRequest = new XMLHttpRequest();
    apodRequest.onreadystatechange = function() {
        //Code here
    };
    apodRequest.open("GET", url, true);
    apodRequest.send(null);
}());

注意我是如何将apodRequest.open("GET", url, true);apodRequest.send(null); 移到onreadystatechange 处理程序之外的。

其次,代替

apodRequest.onreadystatechange = function() {
    if (apodRequest.readyState === 4 && apodRequest.status === 200) {
        //Code here
    }
}

你可以这样做

apodRequest.onload = function() {
        //Code here
};

因为它是在返回响应时触发的事件。所以你不需要if检查里面。

最后,在onload 处理程序中,您有一些错误,例如:

  • data += parsedAPOD; 这是错误的,因为到目前为止 data 是一个 object undefinedparsedAPOD 是一个对象。 在两个对象之间执行+= 不会合并它们。如果要合并两个对象,还有其他方法,例如Object.assign
  • for (i = 0; i &lt; parsedAPOD.length; i++) { ... } 是错误的,因为 parsedAPOD 是一个对象。对象没有length 属性,因此这不是迭代它的正确方法。请改用for ... in ... 循环
  • data += parsedAPOD[i]; 又是错误的,因为这不是合并对象的方法。
  • parsedAPOD[i] 是错误的,因为 i 是一个整数,在这种情况下,parsedAPOD[i] 只是未定义。

希望此分析可以帮助您更正代码。

【讨论】:

    【解决方案2】:

    首先parsedAPOD 是一个对象,parsedAPOD.length 无效。您可以使用for in 循环来遍历对象,如下所示。

    for (var i in parsedAPOD) {
        data += parsedAPOD[i];
        console.log("Parsing lines: <br>" + parsedAPOD[i]);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-16
      • 2018-08-24
      • 1970-01-01
      • 2018-08-20
      • 2018-03-22
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多