在API

时间:2015-12-23 01:17:09

标签: javascript jquery api

我不明白我做错了什么。以下是我在美国人口普查中使用的变量列表的链接:http://api.census.gov/data/2013/pep/natstprc/variables.json

我确实已经意识到你已经可以从下拉列表中看到州的名称,但我的最终目标是能够从下拉列表中选择一个州,并拥有人口和人口密度以及州ID价值或州名(我现在不在乎,因为我感到很沮丧:()出现。在我进入流行音乐或弹出密度之前,我正在尝试使用州名。

我做错了什么?调试器并没有真正帮助我太多。我得到的错误消息是

  

无法读取未定义

的属性'label'

特别是,这是我正在使用的变量:

variables: {
STNAME: {
label: "State name",
concept: "Selectable Geographies"
},

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="css/style.css"></link>
</head>
<body>
    <section id="title">
        <h1>United States Population Search</h1>
        <hr/>
    </section>
    <section id="inputArea">
        <form>
            <select id="inputBox">
                <option value="01">Alabama</option>
                <option value="02">Alaska</option>
                <option value="04">Arizona</option>
                <option value="05">Arkansas</option>
                <option value="06">California</option>
                <option value="08">Colorado</option>
                <option value="09">Connecticut</option>
                <option value="10">Delaware</option>
                <option value="11">District of Columbia</option>
                <option value="12">Florida</option>
                <option value="13">Georgia</option>
                <option value="15">Hawaii</option>
                <option value="16">Idaho</option>
                <option value="17">Illinois</option>
                <option value="18">Indiana</option>
                <option value="19">Iowa</option>
                <option value="20">Kansas</option>
                <option value="21">Kentucky</option>
                <option value="22">Louisiana</option>
                <option value="23">Maine</option>
                <option value="24">Maryland</option>
                <option value="25">Massachusetts</option>
                <option value="26">Michigan</option>
                <option value="27">Minnesota</option>
                <option value="28">Mississippi</option>
                <option value="29">Missouri</option>
                <option value="30">Montana</option>
                <option value="31">Nebraska</option>
                <option value="32">Nevada</option>
                <option value="33">New Hampshire</option>
                <option value="34">New Jersey</option>
                <option value="35">New Mexico</option>
                <option value="36">New York</option>
                <option value="37">North Carolina</option>
                <option value="38">North Dakota</option>
                <option value="39">Ohio</option>
                <option value="40">Oklahoma</option>
                <option value="41">Oregon</option>
                <option value="42">Pennsylvania</option>
                <option value="44">Rhode Island</option>
                <option value="45">South Carolina</option>
                <option value="46">South Dakota</option>
                <option value="47">Tennessee</option>
                <option value="48">Texas</option>
                <option value="49">Utah</option>
                <option value="50">Vermont</option>
                <option value="51">Virginia</option>
                <option value="53">Washington</option>
                <option value="54">West Virginia</option>
                <option value="55">Wisconsin</option>
                <option value="56">Wyoming</option>
            </select>
            <input type="submit" class="searchButton"  value="Search"/>
            <hr/>
        </form>
    </section>
    <section class="searchResults">
        <div class="hiddenTemplates">
            <dl class="stateInformation">
                <dt><u>State ID Value:</u></dt>
                    <dd class="stateName"></dd>
                <dt><u>Population Amount:</u></dt>
                    <dd class="statePopulation"></dd>
                <dt><u>Population Density:</u></dt>
                    <dd class="statePopulationDensity"></dd>
            </dl>
            <div class="errorMessage">
                <p><b>Error Message: Something has gone wrong, try your search again.</b></p>
            </div>

        </div>
    </section>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="js/app.js"></script>
</body>
</html>

的JavaScript / jQuery的:

var data = { "variables": {
"for": {
  "label": "Census API FIPS 'for' clause",
  "concept": "Census API Geography Specification",
  "predicateType": "fips-for",
  "predicateOnly": true
},
"in": {
  "label": "Census API FIPS 'in' clause",
  "concept": "Census API Geography Specification",
  "predicateType": "fips-in",
  "predicateOnly": true
},
"STATE": {
  "label": "Total for US",
  "concept": "Selectable Geographies"
},
"NIM": {
  "label": "Net International Migration",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"STNAME": {
  "label": "State name",
  "concept": "Selectable Geographies"
},
"POP": {
  "label": "Resident population total",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"SUMLEV": {
  "label": "Geographic Summary Level",
  "concept": "Selectable Geographies"
},
"RESIDUAL": {
  "label": "Final residual for total pop",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"DIVISION": {
  "label": "Census Division Code",
  "concept": "Geographic Characteristics"
},
"DOM": {
  "label": "Net Domestic Migration of total Pop",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"DENSITY": {
  "label": "Population Density",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"BIRTHS": {
  "label": "Total Births",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"DATE": {
  "label": "Estimate Date",
  "concept": "Estimate Variables",
  "required": true,
  "predicateType": "int"
},
"REGION": {
  "label": "Census Region Code",
  "concept": "Geographic Characteristics"
},
"DEATHS": {
  "label": "Total Deaths",
  "concept": "Estimate Variables",
  "predicateType": "int"
}
 }
};


//This function fills in the result,
//in our results box, this will give us the name of the US State
var showStateInformation = function(data){

    //var myTest = data.variables.STNAME;
    var label = data.variables.STNAME.label;

    //Puts the name of the state into the state name area
    //var nameOfState = $('.stateName');
    //nameOfState.text(stateSearch);
    //var result = $('.searchResults . hiddenTemplates .stateInformation');
    var nameOfState = $('.stateName');
    nameOfState.text(label);
    //in our results box, this will give us the population for that state
    //based on the Census Data
    //var statePopAmount = result.find('.statePopulation');
    //statePopAmount.text(population);
    //in our results box, this will give us the population density for that state
    //based on the Census Data
    //var statePopDensity = result.find('.statePopulationDensity');
    //statePopDensity.text(populationDensity);

}

//The error message
var showError = function(error){
        var errorElem = $('.searchResults .errorMessage');
        var errorText = '<p>' + error + '</p>';
        errorElem.append(errorText);
}

//This function retrieves the said data
//http://www.census.gov/data/developers/data-sets/population-estimates-and-projections.html
//US, State, and PR Total Population and Components of Change

var getStateInformation = function(stateID){
    //the parameters that we need to pass in our request to the US CENSUS API
    var request = {
        "get": "STNAME",
        "DATE": "6",
        "for": "state:" + stateID,

        "key": 'I was told not to post the key publicly online'
    }

    $.ajax({

        type: "GET",
        data: request,
        url: "http://api.census.gov/data/2013/pep/natstprc",
        dataType: "json",
    })
    //What the function should do if successful
    /*.done(function(){
        var variables = $('#inputBox').val();
        showStateInformation(variables);
    })*/
    .done(showStateInformation)

    //What the function should do if it fails
    .fail(function(jqXHR, error){
        var errorElem = showError(error);
    })


}

$(document).ready(function() {

    /*Clicking the Search Button*/
    $('.searchButton').on('click',function(event){
        event.preventDefault();
        var stateID = $('#inputBox').val();
        getStateInformation(stateID);

    })
})

2 个答案:

答案 0 :(得分:2)

您必须正确声明和初始化对象

variables = {};
variables: {
label: "State name",
concept: "Selectable Geographies"
};

编辑:结果是你编辑问题以使其更清晰。因此,数据来自美国人口普查API。您唯一需要做的就是正确访问对象属性。 假设这是您从美国人口普查中获取的数据:

var data = { "variables": {
"for": {
  "label": "Census API FIPS 'for' clause",
  "concept": "Census API Geography Specification",
  "predicateType": "fips-for",
  "predicateOnly": true
},
"in": {
  "label": "Census API FIPS 'in' clause",
  "concept": "Census API Geography Specification",
  "predicateType": "fips-in",
  "predicateOnly": true
},
"STATE": {
  "label": "Total for US",
  "concept": "Selectable Geographies"
},
"NIM": {
  "label": "Net International Migration",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"STNAME": {
  "label": "State name",
  "concept": "Selectable Geographies"
},
"POP": {
  "label": "Resident population total",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"SUMLEV": {
  "label": "Geographic Summary Level",
  "concept": "Selectable Geographies"
},
"RESIDUAL": {
  "label": "Final residual for total pop",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"DIVISION": {
  "label": "Census Division Code",
  "concept": "Geographic Characteristics"
},
"DOM": {
  "label": "Net Domestic Migration of total Pop",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"DENSITY": {
  "label": "Population Density",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"BIRTHS": {
  "label": "Total Births",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"DATE": {
  "label": "Estimate Date",
  "concept": "Estimate Variables",
  "required": true,
  "predicateType": "int"
},
"REGION": {
  "label": "Census Region Code",
  "concept": "Geographic Characteristics"
},
"DEATHS": {
  "label": "Total Deaths",
  "concept": "Estimate Variables",
  "predicateType": "int"
}
 }
};

访问它的方式是:

var label = data.variables.STNAME.label

你现在的做法有点不对劲。它应该是这样的。

var showStateInformation = function(data){

  var myTest = data.variables.STNAME;

// OMIT THE REST OF THE CODE
}

如果数据仍然是字符串类型,则需要先解析它。但我强烈建议你在调用此函数之前执行此操作并返回正确的对象。但是现在,请先尝试检查

if (typeof data == 'string') {
  data = JSON.parse(data}
}

编辑:原来,JQuery中使用的网址与文中的API网址不同。这是另一个发现的错误:

&#13;
&#13;
var getStateInformation = function(stateID){
//the parameters that we need to pass in our request to the US CENSUS API
var request = {
"get": "STNAME",
"DATE": "6",
"for": "state:" + stateID,

"key": 'I was told not to post the key publicly online'
}

$.ajax({

type: "GET",
url: "http://api.census.gov/data/2013/pep/natstprc/variables.json"
})
//What the function should do if successful
.done(function(data){
console.log(data.variables.STNAME);
})

//What the function should do if it fails
.fail(function(jqXHR, error){
var errorElem = showError(error);
})


}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您收到错误消息'无法读取属性'标签'未定义',因为您正在尝试访问不存在的对象(variables.STNAME)的属性(标签)。从本质上讲,这意味着变量对象的结构不是您所假设的。

最简单的方法是通过添加以下内容打印出来自ajax调用的内容:

(function() {

    document.querySelector('.nav-toggle-btn').addEventListener('click', function (e) {
        document.body.classList.toggle('active-nav');
        e.preventDefault();
    });

})();

在showStateInformation函数的开头。

在警告对话框中,您应该能够看到从API发回的对象的结构,因此可以构造代码以正确访问对象成员。