Javascript NetworkError:未能执行';发送';在';XMLHttpRequest';:未能加载'';:文档已分离
我正在迭代一个数组,向api发送一个请求,以获取lat和long坐标,但只返回一个lat和long坐标,然后得到这个错误 NetworkError:未能对“XMLHttpRequest”执行“发送”:未能加载“”:文档已分离 我使用的代码是Javascript NetworkError:未能执行';发送';在';XMLHttpRequest';:未能加载'';:文档已分离,javascript,xmlhttprequest,Javascript,Xmlhttprequest,我正在迭代一个数组,向api发送一个请求,以获取lat和long坐标,但只返回一个lat和long坐标,然后得到这个错误 NetworkError:未能对“XMLHttpRequest”执行“发送”:未能加载“”:文档已分离 我使用的代码是 function GetEachUsersLatLongCoordinates(zips) { return (TryCatch(function () { let result; let results = [];
function GetEachUsersLatLongCoordinates(zips) {
return (TryCatch(function () {
let result;
let results = [];
let xmlHttp = new XMLHttpRequest();
for (let i = 0; i < zips.length; i++) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
result = JSON.parse(xmlHttp.response);
results.push(result.results[0].geometry.location);
}
}
xmlHttp.open("GET", "https://maps.googleapis.com/maps/api/geocode/json?address=" + parseInt(zips[i]) + "&key=" + GoogleAPIKEY + "", true);
xmlHttp.send(null);
}
return results;
}));
}
函数GetEachUsersLatLongCoordinates(ZIP){
返回(TryCatch(函数(){
让结果;
让结果=[];
设xmlHttp=newxmlhttprequest();
for(设i=0;ilet xmlHttp = new XMLHttpRequest();
在循环内部
您不能在那里返回结果,因为它是异步运行的。您可以将回调传递给GetEachUsersLatLongCoordinates,也可以返回一个承诺。将异步请求视为同步请求还有一个问题。您确实需要重新思考您的代码。@epascarello,我正试图重新思考我编写的内容,并查看您提供的链接。我从打开的链接中删除了true,并在此结果上得到一个错误。push(result.results[0].geometry.location);几何体未定义检查api调用的响应