首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSON访问数据-奇怪的行为

JSON访问数据-奇怪的行为
EN

Stack Overflow用户
提问于 2019-08-18 01:27:50
回答 2查看 33关注 0票数 0

我正在使用Javascript和AJAX使用Javascript API来访问天气数据。我正在检索一个JSON数据文件,并希望访问该文件中的特定变量。当尝试访问"coord“变量时,我得到的响应是"undefined”。奇怪的是,我找不到错误..

我将其作为api_response检索

代码语言:javascript
复制
{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"stations","main":{"temp":293.47,"pressure":1004,"humidity":56,"temp_min":291.15,"temp_max":295.37},"visibility":10000,"wind":{"speed":5.1,"deg":220},"clouds":{"all":40},"dt":1566062145,"sys":{"type":1,"id":1414,"message":0.0096,"country":"GB","sunrise":1566017321,"sunset":1566069657},"timezone":3600,"id":2643743,"name":"London","cod":200}

当尝试通过"api_response.coord“访问"coord”变量时,我得到一个响应"undefined“。

有谁可以帮我?

HTML

代码语言:javascript
复制
<!DOCTYPE html>
<html lang = "en">  <!–– language check you can perform ––>

    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1";>                     <!–– necessary to make the website responsive, zoom level to 1 ––>
        <title>Weather API</title>
        <meta name="description" content="Weather API Test">             <!–– this part will be used in SEM, result of content strategy workshops ––>
        <meta name="author" content="Niels"> 
        <link rel="stylesheet" href="https://use.typekit.net/maw7hdc.css">                        <!–– adobe font import ––>
        <link rel="stylesheet" href="openWeathermap.scss">       <!–– this stylesheet is used for smaller browsers ––>
        <!–– min-width is gebaseerd op de grootte van het browservenster, terwijl min-device-width is gebaseerd op de grootte van het scherm. De breedte van het apparaat wordt door enkele browsers, bijvoorbeeld de oude Android-browser, niet correct gerapporteerd ––>
    </head>

    <body id="body_element">

    <section id="first_section">

        <header id="header_main"></header>

        <div id="api_response"></div>
        <div id="api_specdata"></div>

    </section>

    </body>

    <script src="openWeathermap.js"></script>

    </html>

CSS

代码语言:javascript
复制
html {
    -webkit-font-smoothing: antialiased;  
    height: 100%;
    width: 100%;
    overflow: hidden;
    /* avoiding stairstep lines that mess up the UI, always use!! */
}

/* looking for where a particular element is in the code, just remove css code and see what happens and locate the behavioural element */
body {
    font-family: Segoe, Geneva, sans-serif; 
    /* ??px is standard font size from developer tools */        
}

header {
    height: 100px;
    width: 100%;
    //background-color: $headerColor;
}

#header_main{
    border-bottom: 2px solid black;  
    opacity: 0; 
}

#first_section{
    height: 100vh;
}

#api_response{
    width: fit-content;
    height: fit-content;
}

#api_specdata{
    width: fit-content;
    height: fit-content;
}

Javascript

代码语言:javascript
复制
// Set up HTTP request of type xhr
// status code 200 = success 
var request = new XMLHttpRequest();
var api_key = "f77c39703fb6be71e2c5a96e58edc077";

// Setup our listener to process completed requests
request.onload = function () {

    // Process our return data
    // status code between 200 and 300 indicates success
    if (request.status >= 200 && request.status < 300) {

        console.log('success!', request);
        console.log(request.responseText);

        var api_response = request.responseText;
        document.getElementById("api_response").innerHTML = api_response;

        // get specific data out of the JSON response 
        document.getElementById("api_specdata").innerHTML = api_response.coord;

    // other status codes indicate failure 
    // you could set up a broader response handling if there is a use case for it
    } else {

        console.log('The request failed!');
    }

    // This will run either way
    // All three of these are optional, depending on what you're trying to do
    console.log('This always runs...');
};


// Create and send a GET request
// The first argument is the post type (GET, POST, PUT, DELETE, etc.)
// The second argument is the endpoint URL
request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q=London&APPID=' + api_key);
request.send();
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-08-18 01:33:15

您正在尝试从responseText获取属性coord

responseText不是JSON对象,相反,它是JSON的字符串表示。

您必须解析该字符串,然后访问coord属性。

代码语言:javascript
复制
    var api_response = JSON.parse(request.responseText);

现在您可以访问api_response JSON对象的属性了。

票数 1
EN

Stack Overflow用户

发布于 2019-08-18 01:36:34

XMLHttpRequest.responseText包含响应返回的文本。

如果您希望获得解析结果,则需要使用JSON.parse来解析JSON:

代码语言:javascript
复制
var api_response = JSON.parse(request.responseText);

或者改为使用XMLHttpRequest.response,因为这将包含解析的结果(假设服务器发送正确的内容类型)。

代码语言:javascript
复制
var api_response = request.response;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57538487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档