当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to use a value from an ajax request as the value in an associative array in jquery

问题描述:

I am using ziptastic to return the city and state from a given zip code. It is returning the state as a full name and I am trying to convert the state to the abbreviation once the data is recieved from the ajax request with jquery. The problem I am having is printing the result into my array to get it to return the abbrev. Here is my code so you can get a better idea of what I am trying to do.

var states = new Array (

{'Alabama':'AL'},

{'Alaska':'AK'},

{'Arizona':'AZ'},

{'Arkansas':'AR'},

{'California':'CA'},

{'Colorado':'CO'},

{'Connecticut':'CT'},

{'Delaware':'DE'},

{'Florida':'FL'},

{'Georgia':'GA'},

{'Hawaii':'HI'},

{'Idaho':'ID'},

{'Illinois':'IL'},

{'Indiana':'IN'},

{'Iowa':'IA'},

{'Kansas':'KS'},

{'Kentucky':'KY'},

{'Louisiana':'LA'},

{'Maine':'ME'},

{'Maryland':'MD'},

{'Massachusetts':'MA'},

{'Michigan':'MI'},

{'Minnesota':'MN'},

{'Mississippi':'MS'},

{'Missouri':'MO'},

{'Montana':'MT'},

{'Nebraska':'NE'},

{'Nevada':'NV'},

{'New Hampshire':'NH'},

{'New Jersey':'NJ'},

{'New Mexico':'NM'},

{'New York':'NY'},

{'North Carolina':'NC'},

{'North Dakota':'ND'},

{'Ohio':'OH'},

{'Oklahoma':'OK'},

{'Oregon':'OR'},

{'Pennsylvania':'PA'},

{'Rhode Island':'RI'},

{'South Carolina':'SC'},

{'South Dakota':'SD'},

{'Tennessee':'TN'},

{'Texas':'TX'},

{'Utah':'UT'},

{'Vermont':'VT'},

{'Virginia':'VA'},

{'Washington':'WA'},

{'West Virginia':'WV'},

{'Wisconsin':'WI'},

{'Wyoming':'WY'}

);

$(document).ready(function() {

var zip = $('#zipCode').html().substr(0, 5);

$.ajax({

url: 'http://zip.elevenbasetwo.com/v2/US/'+zip,

cache: false,

type: 'GET',

success: function(result, success) {

$('#city').text(result.city);

$('#city').children().andSelf().each(function(){

$(this).html( capitalize_first_letter($(this).text() ) );

});

$('#state').text(states[result.state]);

},

error: function(result, success) {

$('#city').hide();

$('#state').hide();

$('#zipCode').hide();

}

});

});

My code works before but returned the full name of the state. I am tring to take the result.state and use it in the array to return the abbrev.

网友答案:

The answer above is 100% correct, but there we go just for fun !

var shortcode;

states.forEach(function(state) {
  for (i in state) {
    if (i==result.state) {
      shortcode = state[i];  
    }
  }
})
分享给朋友:
您可能感兴趣的文章:
随机阅读: