user3491987 user3491987 - 6 months ago 29
JSON Question

JavaScript Query Json String from (api.census.gov)

I have an API which should return some text JSon String.

http://api.census.gov/data/2010/sf1?get=P0010001&for=county:013&in=state:08

I wan to use JavaScript to query this API and display in the HTML element. The code looks like this:

//html
<input type="submit" value="Get City" onclick=" getpop()">
//JS:
function getpop() {
var nereq2 = new XMLHttpRequest();
nereq2.open("GET", "http://api.census.gov/data/2010/sf1?get=P0010001&for=county:013&in=state:08", true);
nereq2.onreadystatechange = function () {
if (nereq2.readyState == 4) {
var temp3 = nereq.response; **//problem start at here, which always return empty*******
document.getElementById("fs").innerHTML = temp3;
};
};
nereq2.send();
}


When I click the link it returns the JSon properly, however when I use the code to query, it returns empty. I don't know whether it related to the browser setup or there are some other issues?

Answer

You have a typo. nereq.response should be nereq2.response.

Working JSFiddle - (using https here because JSFiddle requires that)