开发者

Getting a single xml node with javascript

开发者 https://www.devze.com 2023-03-05 16:32 出处:网络
This should be really simple but for some reason I can\'t seem to get it to work; So I have a XML file as follows:

This should be really simple but for some reason I can't seem to get it to work; So I have a XML file as follows:

<board>
     <version>1</version>
<r>
    <c>
        <tile>g</tile>
    </c>

    <c>
        <tile>B</tile>
    </c>
</r>

<r>
    <c>
        <tile>C</tile>
    </c>

    <c>
        <tile>D</tile>
    </c>
</r>
</board>

And some JavaScript like:开发者_开发百科

    function get_cversion(){
    if (window.XMLHttpRequest) { 
        xmlhttp = new XMLHttpRequest(); 
    } 
    else { 
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.open("GET", "board.XML", false); 
    xmlhttp.send(); 
    xmlDoc = xmlhttp.responseXML;
    var mytext = 0


    var x=xmlDoc.getElementsByTagName("version");
    mytext = (x[0].childNodes[0].nodeValue);
    mytext += "";
    document.frmOne.input1.value = ""+mytext;
}

and last, I have a form on the page like this:

<FORM NAME = frmOne>

    1val: <INPUT TYPE = Text NAME = input1 SIZE = 4 value ="">
    <p>
    <Input Type = Button NAME = b1 VALUE = "Save val" onClick = update_XX()>
    <p> 
    <Input Type = Button NAME = b2 VALUE = "WOOOOO" onClick = get_cversion()>
</FORM>

I'm still really new at this whole XML game. I know I must be missing something really obvious but I just cant see it, any help would be greatly appreciated.

Thanks.


You might want to check the status of the request before processing the XML. Your code should look something like this,

    function get_cversion(){
    if (window.XMLHttpRequest) { 
        xmlhttp = new XMLHttpRequest(); 
    } 
    else { 
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.open("GET", "board.XML", false); 
    xmlhttp.send();                   
         if(xmlhttp.status == 200) {
          var xmlDoc = xmlhttp.responseXML;
          var mytext = 0       
          var x=xmlDoc.getElementsByTagName("version");
          mytext = (x[0].childNodes[0].nodeValue);
          mytext += "";
          document.frmOne.input1.value = ""+mytext;            
      }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号