ziptastic响应文本显示'undefined'

时间:2015-08-31 10:30:53

标签: ajax undefined responsetext

我正在尝试使用以下代码从ziptastic获取城市和州数据

function showZipData(){
zipcode = document.getElementById("zipcode").value;
zipData = document.getElementById("divZipDetails")
var client = new XMLHttpRequest();
client.open("GET", "http://www.ziptasticapi.com/"+zipcode, true);
client.onreadystatechange = function() {
if(client.readyState == 4)
{
var elements = client.responseText;
alert(elements.city);
alert(elements.state);
}}client.send();}

但是,两个警报都返回未定义...请帮助...

1 个答案:

答案 0 :(得分:0)

您只是错过了对JSON.parse(..)

的调用
var elements = JSON.parse(client.responseText);
console.log("elements: " + elements);
console.log("elements.city: " + elements.city);
console.log("elements.state: " + elements.state);

适合我!