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



我有一个应该返回一些文本JSon String的API。

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

我想使用 JavaScript 来查询此 API 并显示在 HTML 元素中。代码如下所示:

   //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();
    }

当我单击链接时,它会正确返回 JSon,但是当我使用代码进行查询时,它返回空。我不知道这是否与浏览器设置有关,或者还有其他一些问题?

你有一个错别字。 nereq.response应该是nereq2.response.

工作JSFiddle - (在这里使用https,因为JSFiddle要求这样做

最新更新