ajax poller
程序员文章站
2022-06-24 16:18:03
ajax poller copyright (c) 2006 dthmlgoodies.com, alf magne kalleland this library is f...
ajax poller
copyright (c) 2006 dthmlgoodies.com, alf magne kalleland
this library is free software; you can redistribute it and/or
modify it under the terms of the gnu lesser general public
license as published by the free software foundation; either
version 2.1 of the license, or (at your option) any later version.
this library is distributed in the hope that it will be useful,
but without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose. see the gnu
lesser general public license for more details.
you should have received a copy of the gnu lesser general public
license along with this library; if not, write to the free software
foundation, inc., 51 franklin street, fifth floor, boston, ma 02110-1301 usa
dhtmlgoodies.com., hereby disclaims all copyright interest in this script
written by alf magne kalleland.
alf magne kalleland, 2006
owner of dhtmlgoodies.com
var serversidefile = 'ajax-poller-cast-vote-php.php';
var voteleftimage = 'images/graph_left_1.gif';
var voterightimage = 'images/graph_right_1.gif';
var votecenterimage = 'images/graph_middle_1.gif';
var graphmaxwidth = 130; // it will actually be a little wider than this because of the rounded image at the left and right
var graphminwidth = 15; // minimum size of graph
var pollscrollspeed = 5; // lower = faster
var usecookiestoremembercastedvotes = false; // use cookie to remember casted votes
var txt_totalvotes = 'total number of votes: ';
var ajaxobjects = new array();
var pollvotes = new array();
var pollvotecounted = new array();
var totalvotes = new array();
/* preload images */
var preloadedimages = new array();
preloadedimages[0] = new image();
preloadedimages[0].src = voteleftimage;
preloadedimages[1] = new image();
preloadedimages[1].src = voterightimage;
preloadedimages[2] = new image();
preloadedimages[2].src = votecenterimage;
/*
these cookie functions are downloaded from
http://www.mach5.com/support/analyzer/manual/html/general/cookiesjavascript.htm
*/
function poller_get_cookie(name) {
var start = document.cookie.indexof(name+"=");
var len = start+name.length+1;
if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
if (start == -1) return null;
var end = document.cookie.indexof(";",len);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(len,end));
}
// this function has been slightly modified
function poller_set_cookie(name,value,expires,path,domain,secure) {
expires = expires * 60*60*24*1000;
var today = new date();
var expires_date = new date( today.gettime() + (expires) );
var cookiestring = name + "=" +escape(value) +
( (expires) ? ";expires=" + expires_date.togmtstring() : "") +
( (path) ? ";path=" + path : "") +
( (domain) ? ";domain=" + domain : "") +
( (secure) ? ";secure" : "");
document.cookie = cookiestring;
}
function showvoteresults(pollid,ajaxindex)
{
document.getelementbyid('poller_waitmessage' + pollid).style.display='none';
var xml = ajaxobjects[ajaxindex].response;
xml = xml.replace(/\n/gi,'');
var reg = new regexp("^.*?<pollertitle>(.*?)<.*$","gi");
var pollertitle = xml.replace(reg,'$1');
var resultdiv = document.getelementbyid('poller_results' + pollid);
var titlep = document.createelement('p');
titlep.classname='result_pollertitle';
titlep.innerhtml = pollertitle;
resultdiv.appendchild(titlep);
var options = xml.split(/<option>/gi);
pollvotes[pollid] = new array();
totalvotes[pollid] = 0;
for(var no=1;no<options.length;no++){
var elements = options[no].split(/</gi);
var currentoptionid = false;
for(var no2=0;no2<elements.length;no2++){
if(elements[no2].substring(0,1)!='/'){
var key = elements[no2].replace(/^(.*?)>.*$/gi,'$1');
var value = elements[no2].replace(/^.*?>(.*)$/gi,'$1');
if(key.indexof('optiontext')>=0){
var poption = document.createelement('p');
poption.classname='result_polleroption';
poption.innerhtml = value;
resultdiv.appendchild(poption);
}
if(key.indexof('optionid')>=0){
currentoptionid = value/1;
}
if(key.indexof('votes')>=0){
var votediv = document.createelement('div');
votediv.classname='result_pollgraph';
resultdiv.appendchild(votediv);
var leftimage = document.createelement('img');
leftimage.src = voteleftimage;
votediv.appendchild(leftimage);
var numberdiv = document.createelement('div');
numberdiv.style.backgroundimage = 'url(\'' + votecenterimage + '\')';
numberdiv.innerhtml = '0%';
numberdiv.id = 'result_votetxt' + currentoptionid;
votediv.appendchild(numberdiv);
var rightimage = document.createelement('img');
rightimage.src = voterightimage;
votediv.appendchild(rightimage);
pollvotes[pollid][currentoptionid] = value;
totalvotes[pollid] = totalvotes[pollid]/1 + value/1;
}
}
}
}
var totalvotep = document.createelement('p');
totalvotep.classname = 'result_totalvotes';
totalvotep.innerhtml = txt_totalvotes + totalvotes[pollid];
votediv.appendchild(totalvotep);
setpercentagevotes(pollid);
slidevotes(pollid,0);
}
function setpercentagevotes(pollid)
{
for(var prop in pollvotes[pollid]){
pollvotes[pollid][prop] = math.round( (pollvotes[pollid][prop] / totalvotes[pollid]) * 100);
}
var currentsum = 0;
for(var prop in pollvotes[pollid]){
currentsum = currentsum + pollvotes[pollid][prop]/1;
}
pollvotes[pollid][prop] = pollvotes[pollid][prop] + (100-currentsum);
}
function slidevotes(pollid,currentpercent)
{
currentpercent = currentpercent/1 + 1;
for(var prop in pollvotes[pollid]){
if(pollvotes[pollid][prop]>=currentpercent){
var obj = document.getelementbyid('result_votetxt' + prop);
obj.innerhtml = currentpercent + '%';
obj.style.width = math.max(graphminwidth,math.round(currentpercent/100*graphmaxwidth)) + 'px';
}
}
if(currentpercent<100)settimeout('slidevotes("' + pollid + '","' + currentpercent + '")',pollscrollspeed);
}
function prepareforpollresults(pollid)
{
document.getelementbyid('poller_waitmessage' + pollid).style.display='block';
document.getelementbyid('poller_question' + pollid).style.display='none';
}
function castmyvote(pollid,formobj)
{
var elements = formobj.elements['vote[' + pollid + ']'];
var optionid = false;
for(var no=0;no<elements.length;no++){
if(elements[no].checked)optionid = elements[no].value;
}
poller_set_cookie('dhtmlgoodies_poller_' + pollid,'1',6000000);
if(optionid){
var ajaxindex = ajaxobjects.length;
ajaxobjects[ajaxindex] = new sack();
ajaxobjects[ajaxindex].requestfile = serversidefile + '?pollid=' + pollid + '&optionid=' + optionid;
prepareforpollresults(pollid);
ajaxobjects[ajaxindex].oncompletion = function(){ showvoteresults(pollid,ajaxindex); }; // specify function that will be executed after file has been found
ajaxobjects[ajaxindex].runajax(); // execute ajax function
}
}
function displayresultswithoutvoting(pollid)
{
var ajaxindex = ajaxobjects.length;
ajaxobjects[ajaxindex] = new sack();
ajaxobjects[ajaxindex].requestfile = serversidefile + '?pollid=' + pollid;
prepareforpollresults(pollid);
ajaxobjects[ajaxindex].oncompletion = function(){ showvoteresults(pollid,ajaxindex); }; // specify function that will be executed after file has been found
ajaxobjects[ajaxindex].runajax(); // execute ajax function
}
/* simple ajax code-kit (sack) v1.6.1 */
/* 2005 gregory wild-smith */
/* www.twilightuniverse.com */
/* software licenced under a modified x11 licence,
see documentation or authors website for more details */
function sack(file) {
this.xmlhttp = null;
this.resetdata = function() {
this.method = "post";
this.querystringseparator = "?";
this.argumentseparator = "&";
this.urlstring = "";
this.encodeuristring = true;
this.execute = false;
this.element = null;
this.elementobj = null;
this.requestfile = file;
this.vars = new object();
this.responsestatus = new array(2);
};
this.resetfunctions = function() {
this.onloading = function() { };
this.onloaded = function() { };
this.oninteractive = function() { };
this.oncompletion = function() { };
this.onerror = function() { };
this.onfail = function() { };
};
this.reset = function() {
this.resetfunctions();
this.resetdata();
};
this.createajax = function() {
try {
this.xmlhttp = new activexobject("msxml2.xmlhttp");
} catch (e1) {
try {
this.xmlhttp = new activexobject("microsoft.xmlhttp");
} catch (e2) {
this.xmlhttp = null;
}
}
if (! this.xmlhttp) {
if (typeof xmlhttprequest != "undefined") {
this.xmlhttp = new xmlhttprequest();
} else {
this.failed = true;
}
}
};
this.setvar = function(name, value){
this.vars[name] = array(value, false);
};
this.encvar = function(name, value, returnvars) {
if (true == returnvars) {
return array(encodeuricomponent(name), encodeuricomponent(value));
} else {
this.vars[encodeuricomponent(name)] = array(encodeuricomponent(value), true);
}
}
this.processurlstring = function(string, encode) {
encoded = encodeuricomponent(this.argumentseparator);
regexp = new regexp(this.argumentseparator + "|" + encoded);
vararray = string.split(regexp);
for (i = 0; i < vararray.length; i++){
urlvars = vararray[i].split("=");
if (true == encode){
this.encvar(urlvars[0], urlvars[1]);
} else {
this.setvar(urlvars[0], urlvars[1]);
}
}
}
this.createurlstring = function(urlstring) {
if (this.encodeuristring && this.urlstring.length) {
this.processurlstring(this.urlstring, true);
}
if (urlstring) {
if (this.urlstring.length) {
this.urlstring += this.argumentseparator + urlstring;
} else {
this.urlstring = urlstring;
}
}
// prevents caching of urlstring
this.setvar("rndval", new date().gettime());
urlstringtemp = new array();
for (key in this.vars) {
if (false == this.vars[key][1] && true == this.encodeuristring) {
encoded = this.encvar(key, this.vars[key][0], true);
delete this.vars[key];
this.vars[encoded[0]] = array(encoded[1], true);
key = encoded[0];
}
urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
}
if (urlstring){
this.urlstring += this.argumentseparator + urlstringtemp.join(this.argumentseparator);
} else {
this.urlstring += urlstringtemp.join(this.argumentseparator);
}
}
this.runresponse = function() {
eval(this.response);
}
this.runajax = function(urlstring) {
if (this.failed) {
this.onfail();
} else {
this.createurlstring(urlstring);
if (this.element) {
this.elementobj = document.getelementbyid(this.element);
}
if (this.xmlhttp) {
var self = this;
if (this.method == "get") {
totalurlstring = this.requestfile + this.querystringseparator + this.urlstring;
this.xmlhttp.open(this.method, totalurlstring, true);
} else {
this.xmlhttp.open(this.method, this.requestfile, true);
try {
this.xmlhttp.setrequestheader("content-type", "application/x-www-form-urlencoded")
} catch (e) { }
}
this.xmlhttp.onreadystatechange = function() {
switch (self.xmlhttp.readystate) {
case 1:
self.onloading();
break;
case 2:
self.onloaded();
break;
case 3:
self.oninteractive();
break;
case 4:
self.response = self.xmlhttp.responsetext;
self.responsexml = self.xmlhttp.responsexml;
self.responsestatus[0] = self.xmlhttp.status;
self.responsestatus[1] = self.xmlhttp.statustext;
if (self.execute) {
self.runresponse();
}
if (self.elementobj) {
elemnodename = self.elementobj.nodename;
elemnodename.tolowercase();
if (elemnodename == "input"
|| elemnodename == "select"
|| elemnodename == "option"
|| elemnodename == "textarea") {
self.elementobj.value = self.response;
} else {
self.elementobj.innerhtml = self.response;
}
}
if (self.responsestatus[0] == "200") {
self.oncompletion();
} else {
self.onerror();
}
self.urlstring = "";
break;
}
};
this.xmlhttp.send(this.urlstring);
}
}
};
this.reset();
this.createajax();
}
copyright (c) 2006 dthmlgoodies.com, alf magne kalleland
this library is free software; you can redistribute it and/or
modify it under the terms of the gnu lesser general public
license as published by the free software foundation; either
version 2.1 of the license, or (at your option) any later version.
this library is distributed in the hope that it will be useful,
but without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose. see the gnu
lesser general public license for more details.
you should have received a copy of the gnu lesser general public
license along with this library; if not, write to the free software
foundation, inc., 51 franklin street, fifth floor, boston, ma 02110-1301 usa
dhtmlgoodies.com., hereby disclaims all copyright interest in this script
written by alf magne kalleland.
alf magne kalleland, 2006
owner of dhtmlgoodies.com
复制代码 代码如下:
var serversidefile = 'ajax-poller-cast-vote-php.php';
var voteleftimage = 'images/graph_left_1.gif';
var voterightimage = 'images/graph_right_1.gif';
var votecenterimage = 'images/graph_middle_1.gif';
var graphmaxwidth = 130; // it will actually be a little wider than this because of the rounded image at the left and right
var graphminwidth = 15; // minimum size of graph
var pollscrollspeed = 5; // lower = faster
var usecookiestoremembercastedvotes = false; // use cookie to remember casted votes
var txt_totalvotes = 'total number of votes: ';
var ajaxobjects = new array();
var pollvotes = new array();
var pollvotecounted = new array();
var totalvotes = new array();
/* preload images */
var preloadedimages = new array();
preloadedimages[0] = new image();
preloadedimages[0].src = voteleftimage;
preloadedimages[1] = new image();
preloadedimages[1].src = voterightimage;
preloadedimages[2] = new image();
preloadedimages[2].src = votecenterimage;
/*
these cookie functions are downloaded from
http://www.mach5.com/support/analyzer/manual/html/general/cookiesjavascript.htm
*/
function poller_get_cookie(name) {
var start = document.cookie.indexof(name+"=");
var len = start+name.length+1;
if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
if (start == -1) return null;
var end = document.cookie.indexof(";",len);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(len,end));
}
// this function has been slightly modified
function poller_set_cookie(name,value,expires,path,domain,secure) {
expires = expires * 60*60*24*1000;
var today = new date();
var expires_date = new date( today.gettime() + (expires) );
var cookiestring = name + "=" +escape(value) +
( (expires) ? ";expires=" + expires_date.togmtstring() : "") +
( (path) ? ";path=" + path : "") +
( (domain) ? ";domain=" + domain : "") +
( (secure) ? ";secure" : "");
document.cookie = cookiestring;
}
function showvoteresults(pollid,ajaxindex)
{
document.getelementbyid('poller_waitmessage' + pollid).style.display='none';
var xml = ajaxobjects[ajaxindex].response;
xml = xml.replace(/\n/gi,'');
var reg = new regexp("^.*?<pollertitle>(.*?)<.*$","gi");
var pollertitle = xml.replace(reg,'$1');
var resultdiv = document.getelementbyid('poller_results' + pollid);
var titlep = document.createelement('p');
titlep.classname='result_pollertitle';
titlep.innerhtml = pollertitle;
resultdiv.appendchild(titlep);
var options = xml.split(/<option>/gi);
pollvotes[pollid] = new array();
totalvotes[pollid] = 0;
for(var no=1;no<options.length;no++){
var elements = options[no].split(/</gi);
var currentoptionid = false;
for(var no2=0;no2<elements.length;no2++){
if(elements[no2].substring(0,1)!='/'){
var key = elements[no2].replace(/^(.*?)>.*$/gi,'$1');
var value = elements[no2].replace(/^.*?>(.*)$/gi,'$1');
if(key.indexof('optiontext')>=0){
var poption = document.createelement('p');
poption.classname='result_polleroption';
poption.innerhtml = value;
resultdiv.appendchild(poption);
}
if(key.indexof('optionid')>=0){
currentoptionid = value/1;
}
if(key.indexof('votes')>=0){
var votediv = document.createelement('div');
votediv.classname='result_pollgraph';
resultdiv.appendchild(votediv);
var leftimage = document.createelement('img');
leftimage.src = voteleftimage;
votediv.appendchild(leftimage);
var numberdiv = document.createelement('div');
numberdiv.style.backgroundimage = 'url(\'' + votecenterimage + '\')';
numberdiv.innerhtml = '0%';
numberdiv.id = 'result_votetxt' + currentoptionid;
votediv.appendchild(numberdiv);
var rightimage = document.createelement('img');
rightimage.src = voterightimage;
votediv.appendchild(rightimage);
pollvotes[pollid][currentoptionid] = value;
totalvotes[pollid] = totalvotes[pollid]/1 + value/1;
}
}
}
}
var totalvotep = document.createelement('p');
totalvotep.classname = 'result_totalvotes';
totalvotep.innerhtml = txt_totalvotes + totalvotes[pollid];
votediv.appendchild(totalvotep);
setpercentagevotes(pollid);
slidevotes(pollid,0);
}
function setpercentagevotes(pollid)
{
for(var prop in pollvotes[pollid]){
pollvotes[pollid][prop] = math.round( (pollvotes[pollid][prop] / totalvotes[pollid]) * 100);
}
var currentsum = 0;
for(var prop in pollvotes[pollid]){
currentsum = currentsum + pollvotes[pollid][prop]/1;
}
pollvotes[pollid][prop] = pollvotes[pollid][prop] + (100-currentsum);
}
function slidevotes(pollid,currentpercent)
{
currentpercent = currentpercent/1 + 1;
for(var prop in pollvotes[pollid]){
if(pollvotes[pollid][prop]>=currentpercent){
var obj = document.getelementbyid('result_votetxt' + prop);
obj.innerhtml = currentpercent + '%';
obj.style.width = math.max(graphminwidth,math.round(currentpercent/100*graphmaxwidth)) + 'px';
}
}
if(currentpercent<100)settimeout('slidevotes("' + pollid + '","' + currentpercent + '")',pollscrollspeed);
}
function prepareforpollresults(pollid)
{
document.getelementbyid('poller_waitmessage' + pollid).style.display='block';
document.getelementbyid('poller_question' + pollid).style.display='none';
}
function castmyvote(pollid,formobj)
{
var elements = formobj.elements['vote[' + pollid + ']'];
var optionid = false;
for(var no=0;no<elements.length;no++){
if(elements[no].checked)optionid = elements[no].value;
}
poller_set_cookie('dhtmlgoodies_poller_' + pollid,'1',6000000);
if(optionid){
var ajaxindex = ajaxobjects.length;
ajaxobjects[ajaxindex] = new sack();
ajaxobjects[ajaxindex].requestfile = serversidefile + '?pollid=' + pollid + '&optionid=' + optionid;
prepareforpollresults(pollid);
ajaxobjects[ajaxindex].oncompletion = function(){ showvoteresults(pollid,ajaxindex); }; // specify function that will be executed after file has been found
ajaxobjects[ajaxindex].runajax(); // execute ajax function
}
}
function displayresultswithoutvoting(pollid)
{
var ajaxindex = ajaxobjects.length;
ajaxobjects[ajaxindex] = new sack();
ajaxobjects[ajaxindex].requestfile = serversidefile + '?pollid=' + pollid;
prepareforpollresults(pollid);
ajaxobjects[ajaxindex].oncompletion = function(){ showvoteresults(pollid,ajaxindex); }; // specify function that will be executed after file has been found
ajaxobjects[ajaxindex].runajax(); // execute ajax function
}
复制代码 代码如下:
/* simple ajax code-kit (sack) v1.6.1 */
/* 2005 gregory wild-smith */
/* www.twilightuniverse.com */
/* software licenced under a modified x11 licence,
see documentation or authors website for more details */
function sack(file) {
this.xmlhttp = null;
this.resetdata = function() {
this.method = "post";
this.querystringseparator = "?";
this.argumentseparator = "&";
this.urlstring = "";
this.encodeuristring = true;
this.execute = false;
this.element = null;
this.elementobj = null;
this.requestfile = file;
this.vars = new object();
this.responsestatus = new array(2);
};
this.resetfunctions = function() {
this.onloading = function() { };
this.onloaded = function() { };
this.oninteractive = function() { };
this.oncompletion = function() { };
this.onerror = function() { };
this.onfail = function() { };
};
this.reset = function() {
this.resetfunctions();
this.resetdata();
};
this.createajax = function() {
try {
this.xmlhttp = new activexobject("msxml2.xmlhttp");
} catch (e1) {
try {
this.xmlhttp = new activexobject("microsoft.xmlhttp");
} catch (e2) {
this.xmlhttp = null;
}
}
if (! this.xmlhttp) {
if (typeof xmlhttprequest != "undefined") {
this.xmlhttp = new xmlhttprequest();
} else {
this.failed = true;
}
}
};
this.setvar = function(name, value){
this.vars[name] = array(value, false);
};
this.encvar = function(name, value, returnvars) {
if (true == returnvars) {
return array(encodeuricomponent(name), encodeuricomponent(value));
} else {
this.vars[encodeuricomponent(name)] = array(encodeuricomponent(value), true);
}
}
this.processurlstring = function(string, encode) {
encoded = encodeuricomponent(this.argumentseparator);
regexp = new regexp(this.argumentseparator + "|" + encoded);
vararray = string.split(regexp);
for (i = 0; i < vararray.length; i++){
urlvars = vararray[i].split("=");
if (true == encode){
this.encvar(urlvars[0], urlvars[1]);
} else {
this.setvar(urlvars[0], urlvars[1]);
}
}
}
this.createurlstring = function(urlstring) {
if (this.encodeuristring && this.urlstring.length) {
this.processurlstring(this.urlstring, true);
}
if (urlstring) {
if (this.urlstring.length) {
this.urlstring += this.argumentseparator + urlstring;
} else {
this.urlstring = urlstring;
}
}
// prevents caching of urlstring
this.setvar("rndval", new date().gettime());
urlstringtemp = new array();
for (key in this.vars) {
if (false == this.vars[key][1] && true == this.encodeuristring) {
encoded = this.encvar(key, this.vars[key][0], true);
delete this.vars[key];
this.vars[encoded[0]] = array(encoded[1], true);
key = encoded[0];
}
urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
}
if (urlstring){
this.urlstring += this.argumentseparator + urlstringtemp.join(this.argumentseparator);
} else {
this.urlstring += urlstringtemp.join(this.argumentseparator);
}
}
this.runresponse = function() {
eval(this.response);
}
this.runajax = function(urlstring) {
if (this.failed) {
this.onfail();
} else {
this.createurlstring(urlstring);
if (this.element) {
this.elementobj = document.getelementbyid(this.element);
}
if (this.xmlhttp) {
var self = this;
if (this.method == "get") {
totalurlstring = this.requestfile + this.querystringseparator + this.urlstring;
this.xmlhttp.open(this.method, totalurlstring, true);
} else {
this.xmlhttp.open(this.method, this.requestfile, true);
try {
this.xmlhttp.setrequestheader("content-type", "application/x-www-form-urlencoded")
} catch (e) { }
}
this.xmlhttp.onreadystatechange = function() {
switch (self.xmlhttp.readystate) {
case 1:
self.onloading();
break;
case 2:
self.onloaded();
break;
case 3:
self.oninteractive();
break;
case 4:
self.response = self.xmlhttp.responsetext;
self.responsexml = self.xmlhttp.responsexml;
self.responsestatus[0] = self.xmlhttp.status;
self.responsestatus[1] = self.xmlhttp.statustext;
if (self.execute) {
self.runresponse();
}
if (self.elementobj) {
elemnodename = self.elementobj.nodename;
elemnodename.tolowercase();
if (elemnodename == "input"
|| elemnodename == "select"
|| elemnodename == "option"
|| elemnodename == "textarea") {
self.elementobj.value = self.response;
} else {
self.elementobj.innerhtml = self.response;
}
}
if (self.responsestatus[0] == "200") {
self.oncompletion();
} else {
self.onerror();
}
self.urlstring = "";
break;
}
};
this.xmlhttp.send(this.urlstring);
}
}
};
this.reset();
this.createajax();
}