日期:2014-05-16 浏览次数:20817 次
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Ajax即时后台添加</title>
<script language="javascript" type="text/javascript">
    function initXmlHttpReq(){
        var browserVersion=navigator.appVersion;
        var xmlhttpReq;
        if(window.XmlHttpRequest){                                //IE7+、Firefox、Chrome、Safari 以及 Opera
            xmlhttpReq=new XmlHttpRequest();
        }else if(window.ActiveXObject){                        //IE6及更低版本
            var a=['MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','MICROSOFT.XMLHTTP.1.0','MICROSOFT.XMLHTTP.1','MICROSOFT.XMLHTTP'];
            for (var i=0;i<a.length;i++){
                if(browserVersion.indexOf("MSIE 6.0")){
                    xmlhttpReq=new ActiveXObject("MSXML2.XMLHTTP");
                    break;
                }else{
                    xmlhttpReq=new ActiveXObject(a[i]);
                    if(xmlhttpReq){
                        break;
                    }
                }
            }
        }
        return xmlhttpReq;    
    }
    function addVote(){
        var xmlhttp=initXmlHttpReq();
        var vote=document.getElementById("vote").value;
        xmlhttp.onreadystatechange=function(){
            if((xmlhttp.readyState==4)&&(xmlhttp.status==200)){
                alert("发表成功");
                showVote();
            }
        }
        xmlhttp.open("GET","ajax_php.php?action=add&vote="+vote,true);
        xmlhttp.send();
    }
    function showVote(){
        var xmlhttp=initXmlHttpReq();
        xmlhttp.onreadystatechange=function(){
            if((xmlhttp.readyState==4)&&(xmlhttp.status==200)){
                document.getElementById("myDiv").innerHTML.responseText;
            }
        }
        xmlhttp.open("GET","ajax_php.php?action=show",true);
        xmlhttp.send();
    }
</script>
</head>
<body>
    <div id="myDiv"></div>
    <input type="text" id="vote"/>
    <input type="button" onclick="addVote()" value="AddVote"/>
</body>
</html>
<?php
global $ceshi;
if((isset($_GET['action']))&&('add'==$_GET['action'])){
    $ceshi=$_GET['vote'];
}else{
    echo $ceshi;
}
?>
function initXmlHttpReq(){
        var xmlhttpReq = false;
            try {
                xmlhttpReq = new XMLHttpRequest();
            } catch (trymicrosoft) {
            try {
                xmlhttpReq = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (othermicrosoft) {
            try {
                xmlhttpReq = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                xmlhttpReq = false;
              }
            }
        }    
        return xmlhttpReq;
    }
------解决方案-----