如何使用JavaScript将数据从一个功能转移到另一个功能

时间:2019-03-26 18:46:38

标签: javascript html xml function

大家好,我有问题。 我正在建立一个网站,我想从具有两个不同功能的两个不同xml文件中获取数据。 ShowResult用于获取游戏得分和特定用户的名称。 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>

1 个答案:

答案 0 :(得分:0)

我设法解决了我的问题。

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