这让我发疯。我在 VB 中完成了这个工作,但无法让这个代码工作。将 URL 拼凑在一起可以正常工作,因为我可以输出它,然后复制地址并生成输出。但是,在此代码中,我没有收到任何返回信息,并且触发了网络错误警报。我在这里查看了其他线程,但我看不出我做错了什么,这意味着它就在我面前。任何帮助将不胜感激。
这是代码:
<!DOCTYPE html>
<html>
<body>
<label for="streetInput">Street:</label>
<input type="text" id="streetInput"><br><br>
<label for="cityInput">City:</label>
<input type="text" id="cityInput"><br><br>
<label for="stateInput">State:</label>
<input type="text" id="stateInput"><br><br>
<label for="zipInput">Zip:</label>
<input type="text" id="zipInput"><br><br>
<button onclick="searchCensusData()">Search Census Data</button>
<p id="result"></p>
<script>
function searchCensusData() {
const street = encodeURIComponent(document.getElementById('streetInput').value);
const city = encodeURIComponent(document.getElementById('cityInput').value);
const state = encodeURIComponent(document.getElementById('stateInput').value);
const zip = encodeURIComponent(document.getElementById('zipInput').value);
const newstreet = street.replaceAll("%20", "+");
const jjson = "json";
const benchmark = "Public_AR_Current";
const vintage = "Current_Current";
const combined = newstreet.concat('&city=',city,'&state=',state,'&zip=',zip,'&benchmark=',benchmark,'&vintage=',vintage,'&format=',jjson);
const Url = "https://geocoding.geo.census.gov/geocoder/geographies/address?street=";
const apiUrl = Url.concat(combined);
document.getElementById('result').innerText = apiUrl;
const xhr = new XMLHttpRequest();
xhr.open("GET",apiUrl);
xhr.send();
xhr.onerror = function() { // only triggers if the request couldn't be made at all
alert(`Network Error`);
};
const response = xhr.responseText;
const geoInfoPos = response.indexOf("Census Tracts");
const geoInfo = response.substr(geoInfoPos,11);
}
</script>
</body>
</html>
您没有使用 load 事件,因此您尝试在返回之前读取响应。您正确处理错误状态。您想对负载执行相同的操作。
xhr.onload = function () {
console.log(xhr.responseText);
};