JavaScript与CGI通过XML进行数据传送
JavaScript部分程序
var xmlHttp
var writeHttp
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function update()
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="/cgi-bin/rtd.cgi"
url=url+"?sid="+Math.random()
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
xmlDoc=xmlHttp.responseXML;
for(var i=0; i<3; i++)
{
document.getElementById("rtd"+(i+1)).value = xmlDoc.getElementsByTagName("para")[i].childNodes[0].nodeValue+" V";
}
/*
document.getElementById("rtd1").value = xmlDoc.getElementsByTagName("para")[0].childNodes[0].nodeValue+" V";
document.getElementById("rtd2").value = xmlDoc.getElementsByTagName("para")[1].childNodes[0].nodeValue+" V";
document.getElementById("rtd3").value = xmlDoc.getElementsByTagName("para")[2].childNodes[0].nodeValue+" V";
*/
}
}
function load()
{
setInterval(update, 1000);
}
function toPage(page)
{
window.location=page;
}
function writeOne()
{
writeHttp=GetXmlHttpObject()
if (writeHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="/cgi-bin/write.cgi"
url=url+"?sid="+Math.random()
writeHttp.onreadystatechange=writeOneResp
writeHttp.open("GET",url,true)
writeHttp.send(null);
}
function writeOneResp()
{
if (writeHttp.readyState==4 || writeHttp.readyState=="complete")
{
xmlDoc2=writeHttp.responseXML;
window.alert(xmlDoc2.getElementsByTagName("para")[0].childNodes[0].nodeValue);
}
}
CGI部分程序
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Content-type:text/xml\n\n");
printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
printf("<data>");
srand(time(0));
float rtd1=55+rand()%100/100.0;
float rtd2=110+rand()%100/100.0;
float rtd3=220+rand()%100/100.0;
printf("<para id=\"rtd1\">%.4f</para>", rtd1);
printf("<para id=\"rtd2\">%.4f</para>", rtd2);
printf("<para id=\"rtd3\">%.4f</para>", rtd3);
printf("</data>");
return 0;
}