-4

我的服务器中有以下 xml

<root>
<name> arun</name>
<score> 20 </score>
<name> varun</name>
<score> 120 </score>
</root> 

我可以通过在 xml 中编写一些 javascripts 并将详细信息检索为 html 来获得最高分吗

4

1 回答 1

0

这是您可以尝试的一些半代码,它可以做得更好,但这是一个很好的起点。请使用带有firebug插件的Firefox或Chrome进行测试,按F12打开开发工具并检查控制台是否有错误

var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

httpRequest.onreadystatechange = function(){
  if (httpRequest.readyState === 4 && httpRequest.status === 200) {
    // everything is good, the response is received
    // the responseXML should be your xml file as a JS document object
    console.log(this.responseXML);
    // get all the score elements
    var scores = this.responseXML.getElementsByTagName("score");
    var arr=[]; //array containing score values
    var tmpNum; // temporary store score value in here
    for(var i=0;i<scores.length;i++){
      //try to convert the score element innerHTML to an integer
      tmpNum=parseInt(scores[i].innerHTML.trim(),10);
      // if tmpNum is a number then store it in the scores array
      if(!isNaN(tmpNum)){
        arr.push(tmpNum);
      }
    }
    //sort the arr (lowest first)
    arr.sort();
    // get last element (is highest)
    console.log("Highest score:",arr[arr.length-1]);

  } else {
    // still not ready
  }
};
httpRequest.open('GET', "your URL");
httpRequest.send();
于 2013-05-06T06:29:20.387 回答