我无法在javascript函数中返回responseXML值

我无法在javascript函数中返回responseXML值,javascript,asynchronous,xmlhttprequest,Javascript,Asynchronous,Xmlhttprequest,我有下面的javascript代码,它应该返回给定位置的大地水准面。我用CORS插件在Chromium浏览器中进行了测试。它检索ID,但我无法从函数外部获取该值 我不熟悉javascript,但我读过这些,并在发布问题之前进行了搜索 这是你的电话号码 我错过了什么 编辑:多亏了版主,他们把我的问题重定向到了正确的轨道上。 那么,如何修复代码以绕过异步调用呢 var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function(

我有下面的javascript代码,它应该返回给定位置的大地水准面。我用CORS插件在Chromium浏览器中进行了测试。它检索ID,但我无法从函数外部获取该值

我不熟悉javascript,但我读过这些,并在发布问题之前进行了搜索

这是你的电话号码

我错过了什么

编辑:多亏了版主,他们把我的问题重定向到了正确的轨道上。 那么,如何修复代码以绕过异步调用呢

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        myFunction(xhttp);
    }
};
var mylocation = 'istanbul'
xhttp.open("GET", "http://api.geonames.org/search?q= + mylocation + &username=kennsully", true);
xhttp.send();

function myFunction(arg) {
     var xmlDoc = arg.responseXML;
     var geoid = xmlDoc.getElementsByTagName("geonameId")[1].childNodes[0].nodeValue;

    // document.write(geoid); // when uncommented it prints the id 891501

   // console.log(geoid);
    return geoid;


};
var geoid = myFunction();  
console.log(geoid);// <=  Uncaught TypeError: Cannot read property 'responseXML' of undefined
at myFunction 
var xhttp=new-XMLHttpRequest();
xhttp.onreadystatechange=函数(){
如果(xhttp.readyState==4&&xhttp.status==200){
myFunction(xhttp);
}
};
var mylocation=‘伊斯坦布尔’
xhttp.open(“GET”http://api.geonames.org/search?q= +mylocation+&用户名=kennsully“,true);
xhttp.send();
函数myFunction(arg){
var xmlDoc=arg.responseXML;
var geoid=xmlDoc.getElementsByTagName(“geonameId”)[1]。childNodes[0]。nodeValue;
//document.write(geoid);//未注释时,它将打印id 891501
//控制台日志(大地水准面);
返回大地水准面;
};
var geoid=myFunction();

console.log(大地水准面);// 您没有正确插入“mylocation”变量。您当前将其作为字符串的一部分

改用这个:

xhttp.open("GET", "http://api.geonames.org/search?q=" + mylocation + "&username=kennsully", true);

另外,将“responseText”传递给“myFunction”函数:

if (this.readyState == 4 && this.status == 200) {
    var res = this.responseText;
    myFunction(res);
}

我试过了,没什么变化。所以,把“responseText”传递给你的“myFunction”函数。我已经更新了我的答案。