如何使用javascript将数据从一个函数传输到另一个函数



大家好,我有问题。我正在建立一个网站,我想从具有两种不同功能的两个不同的 xml 文件中获取数据。显示结果用于获取游戏分数和特定用户的名称。GiveFeedback 还需要第一个函数的分数,以便从不同的 xml 文件中获取有关此分数的合适反馈。

我没有收到错误消息。我唯一的问题是第二个函数(giveFeedback(无法从xml中获取数据,因为它需要第一个函数(showResults(中的一个变量(分数(。这两个函数都可以独立工作,但我无法将分数数据从 showResults "传输"到 giveFeedback。如何将分数数据传输到函数 GiveFeedback,或者有更好的方法来解决此问题?谢谢!

我尝试了一些已经发布的解决方案(全局变量,在第二个,..中插入第一个函数(,但不幸的是我没有设法让它运行。

<script>    
var xhttp = new XMLHttpRequest(); 
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    showResult(xhttp.responseXML); 
    }
}; 
xhttp.open("GET", "user.xml", true); 
xhttp.send();

function showResult(xml) {  
    var name = "";
    var score = ""; 
    path1 = "/userdb/user/name";
    path2 = "/userdb/user/score";
    var nodes = xml.evaluate(path1, xml, null, XPathResult.ANY_TYPE, null); var result = nodes.iterateNext();
    name = result.childNodes[0].nodeValue;
    var nodes = xml.evaluate(path2, xml, null, XPathResult.ANY_TYPE, null); var result = nodes.iterateNext();
    //Thats wehere the variable (score) is, which i need for the second function (giveFeedback)
    score = result.childNodes[0].nodeValue;
    document.getElementById("user").innerHTML = "Congratulations " + name + ", you made " + score; 
}

var xhttp2 = new XMLHttpRequest(); 
xhttp2.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        givefeedback(xhttp2.responseXML); 
    }
}; 
xhttp2.open("GET", "feedback.xml", true); 
xhttp2.send();

function givefeedback(xml) { 
    var feedback = "";
    // This is where it´s needed
    if (score > 1){
        path = "/feedback/congratulations[percentage=25]/text";
    }
    else if (score > 8){
        path = "/feedback/congratulations[percentage=50]/text";
    }
    var nod = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null); 
    var res = nod.iterateNext();
    feedback = res.childNodes[0].nodeValue;

    document.getElementById("feedback").innerHTML = feedback; 
}
</script>

我设法解决了我的问题。

首先,我必须在函数外部声明一个全局变量。然后我必须将获取的变量(分数(转换为数字。

最新更新