简体   繁体   中英

Reading xml value with javascript

I'm trying to make a small project based on FlyPORT WiFi

Anyways, i need to read a value from xml file and plot it in the web page via javascript. The problem is that when I put the value to a variable it seems that it's not a valid number. Here is my code:

index.html

    <html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<script language="javascript" type="text/javascript" src="jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="jquery.jqplot.min.js"></script>
<script type="text/javascript" src="mchp.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.jqplot.css" />
</head>
<body>

<div id="chartdiv" style="height:400px;width:600px;" align="center"></div>
<script type="text/javascript">
var x=getXMLValue('status.xml','key');
var y=parseFloat(x);

$.jqplot('chartdiv',  [[[-24, y],[-20,5.12],[-17,13.1],[-15,33.6],[-7,85.9],[-2,219.9]]],
    {
        axes:{
            xaxis:{min:-24, max:-1},
            yaxis:{min:-24, max:50+2}
        },
        grid: {
            background: 'rgba(00,00,00,0.0)',
            drawBorder: false,
            shadow: false,
            gridLineColor: '#FFFFFF',
            gridLineWidth: 2},
        title: 'Temperature',
        animate : true,
        showTicks: true,   
        series: [{color: '#FF0000'}],
    }
    );

</script>
</body>
</html>

status.xml

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <key>5</key>
</response>

The file mchp.js was not written by me.You can see an example of using it here .

// Determines when a request is considered "timed out"
var timeOutMS = 5000; //ms

// Stores a queue of AJAX events to process
var ajaxList = new Array();

// Initiates a new AJAX command
//  url: the url to access
//  container: the document ID to fill, or a function to call with response XML (optional)
//  repeat: true to repeat this call indefinitely (optional)
//  data: an URL encoded string to be submitted as POST data (optional)
function newAJAXCommand(url, container, repeat, data)
{
    // Set up our object
    var newAjax = new Object();
    var theTimer = new Date();
    newAjax.url = url;
    newAjax.container = container;
    newAjax.repeat = repeat;
    newAjax.ajaxReq = null;

    // Create and send the request
    if(window.XMLHttpRequest) {
        newAjax.ajaxReq = new XMLHttpRequest();
        newAjax.ajaxReq.open((data==null)?"GET":"POST", newAjax.url, true);
        newAjax.ajaxReq.send(data);
    // If we're using IE6 style (maybe 5.5 compatible too)
    } else if(window.ActiveXObject) {
        newAjax.ajaxReq = new ActiveXObject("Microsoft.XMLHTTP");
        if(newAjax.ajaxReq) {
            newAjax.ajaxReq.open((data==null)?"GET":"POST", newAjax.url, true);
            newAjax.ajaxReq.send(data);
        }
    }

    newAjax.lastCalled = theTimer.getTime();

    // Store in our array
    ajaxList.push(newAjax);
}

// Loops over all pending AJAX events to determine if any action is required
function pollAJAX() {   
    var curAjax = new Object();
    var theTimer = new Date();
    var elapsed;

    // Read off the ajaxList objects one by one
    for(i = ajaxList.length; i > 0; i--)
    {
        curAjax = ajaxList.shift();
        if(!curAjax)
            continue;
        elapsed = theTimer.getTime() - curAjax.lastCalled;

        // If we suceeded
        if(curAjax.ajaxReq.readyState == 4 && curAjax.ajaxReq.status == 200) {
            // If it has a container, write the result
            if(typeof(curAjax.container) == 'function'){
                curAjax.container(curAjax.ajaxReq.responseXML.documentElement);
            } else if(typeof(curAjax.container) == 'string') {
                document.getElementById(curAjax.container).innerHTML = curAjax.ajaxReq.responseText;
            } // (otherwise do nothing for null values)

            curAjax.ajaxReq.abort();
            curAjax.ajaxReq = null;

            // If it's a repeatable request, then do so
            if(curAjax.repeat)
                newAJAXCommand(curAjax.url, curAjax.container, curAjax.repeat);
            continue;
        }

        // If we've waited over 1 second, then we timed out
        if(elapsed > timeOutMS) {
            // Invoke the user function with null input
            if(typeof(curAjax.container) == 'function'){
                curAjax.container(null);
            } else {
                // Alert the user
                alert("Command failed.\nConnection to development board was lost.");
            }

            curAjax.ajaxReq.abort();
            curAjax.ajaxReq = null;

            // If it's a repeatable request, then do so
            if(curAjax.repeat)
                newAJAXCommand(curAjax.url, curAjax.container, curAjax.repeat);
            continue;
        }

        // Otherwise, just keep waiting
        ajaxList.push(curAjax);
    }

    // Call ourselves again in 100ms
    setTimeout("pollAJAX()",100);

}

// Parses the xmlResponse returned by an XMLHTTPRequest object
//  xmlData: the xmlData returned
//  field: the field to search for
function getXMLValue(xmlData, field) {
    try {
        if(xmlData.getElementsByTagName(field)[0].firstChild.nodeValue)
            return xmlData.getElementsByTagName(field)[0].firstChild.nodeValue;
        else
            return null;
    } catch(err) { return null; }
}

//kick off the AJAX Updater
setTimeout("pollAJAX()",500);

I think the jquery and jqplot files are not important in this case but I can provide links if needed. I think the problem is with reading or converting the xml data. Thank you in advance for the help!

您要解析的不是xml,而是字符串'status.xml'。

The problem is that you are calling getXMLValue in the wrong way. getXMLValue expects a parsed xml document, not a string with a url/file name. You need to call an url that is returning the status.xml. For example, since you are using jQuery you could do something like:

jQuery.ajax({
  type : "GET",
  url : "http://localhost/status.xml",
  dataType : "xml",
  success : function(xml) {
    var y = parseFloat(getXMLValue(xml,key));
    jQuery.jqplot('chartdiv',  [[[-24, y],[-20,5.12],[-17,13.1],[-15,33.6],[-7,85.9],[-2,219.9]]],{
        axes:{
        xaxis:{min:-24, max:-1},
            yaxis:{min:-24, max:50+2}
        },
        grid: {
            background: 'rgba(00,00,00,0.0)',
            drawBorder: false,
            shadow: false,
            gridLineColor: '#FFFFFF',
            gridLineWidth: 2},
        title: 'Temperature',
        animate : true,
        showTicks: true,   
        series: [{color: '#FF0000'}],
    });
    },
    error : function(xhr) {
        alert(xhr.responseText);
    }
});

this is at least one problem I spotted. There may be some other issues with your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM