AJAX POST实例

=====ajax.html=====

<!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 type="text/javascript">
<!--
//Ajax是建立在XMLHttp组件下的技术,本例详细语法参考压缩包内xmlhttp手册

var xmlHttp
//建立XMLHTTP对象调用MS的ActiveXObject方法,如果成功(IE浏览器)则使用MS ActiveX实例化创建一个XMLHTTP对象非IE则转用建立一个本地Javascript对象的XMLHttp对象(此方法确保不同浏览器下对AJAX的支持)


function createXMLHttp(){
if(window.XMLHttpRequest){ // Mozilla 浏览器
xmlHttp = new XMLHttpRequest();
}else if (window.ActiveXObject){ // IE 浏览器
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
}


//建立主过程
function startXMLHttp(){
    createXMLHttp(); //建立xmlHttp 对象
 var send_string="name="+document.getElementById("name").value;
 send_string= encodeURI(send_string)
// alert(document.getElementById("text").value);
// return;
       xmlHttp.open("post","1.asp",true); //传送方式 读取的页面 异步与否
// xmlHttp.setRequestHeader("cache-control","no-cache");
   xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  xmlHttp.onreadystatechange =dodo; //xmlHttp下的onreadystatechange方法控制传送过程

    xmlHttp.send(send_string); //发送
}

function dodo(){
    if(xmlHttp.readystate==4){ // xmlHttp下的readystate方法 4表示传送完毕
        if(xmlHttp.status==200){ // xmlHttp的status方法读取状态(服务器HTTP状态码) 200对应OK 404对应Not Found(未找到)等
     document.getElementById("content").innerHTML=xmlHttp.responseText //xmlHttp的responseText方法 得到读取页数据
           }
    
}

}
-->
</script>
</head>

<body>
<span id="content">替换内容</span><br>
<input type="button" onclick="javascript:startXMLHttp()" value="AJAX获取"/>
<form id="form1" name="form1" method="post" action="">
  <label>
  <input type="text" name="textfield" id="name" />
  </label>
</form>
</body>
</html>

========1.asp===============


<%
'-------------------------------------------
'//禁止缓存该页 让AJAX读取该页始终为最新而非过期缓存页
Response.Expires = 0
Response.Expiresabsolute = Now() - 1
Response.AddHeader "pragma","no-cache"
Response.AddHeader "cache-control","private"
Response.CacheControl = "no-cache"
'-------------------------------------------
response.Charset="GB2312" '//数据返回的编码类型 显示中文数据必须

'-------------------------------------------
response.Write(now())'//得到当前时间
Dim Content
Content = Request.Form("name")
Response.Write(Content)
%>
在此说明一点xmlHttp.onreadystatechange这个xmlHttp下的onreadystatechange方法控制传送过程必须放在最后调用,就是尽量放在xmlHttp.setRequestHeader的后面。

否则就会导致只更新一次页面内容,而不再更新,很容易犯的错误

原文地址:https://www.cnblogs.com/yeye518/p/2231708.html