读书人

哪位高手能帮小弟我解释下这段代码带

发布时间: 2012-01-01 23:10:55 作者: rapoo

谁能帮我解释下这段代码,带我入AJAX的门
<script type= "text/javascript " language= "javascript ">

var xmlhttp;

function username_changed()
{

try{
xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP ");
}catch(e){
try{
xmlhttp = new ActiveXObject( "Msxml2.XMLHTTP ");
}catch(e){
try{
xmlhttp = new XMLHttpRequest();
}catch(e){
xmlhttp = null;
}
}
}

var url= "signup-ajax.aspx?username= "+document.getElementById( "ctl00_ContentPlaceHolder1_TextBoxusername ").value;

xmlhttp.onreadystatechange = getReady;
xmlhttp.open( "GET ",url,true);
xmlhttp.send(null);
}

function getReady()
{
if(xmlhttp==null)
return;

if(xmlhttp.readyState == 4)
{
if(xmlhttp.status == 200)
{
document.getElementById( 'hint_username ').innerHTML = xmlhttp.responseText;
}
xmlhttp = null;
}
}


////======================================


function password_changed()
{
var p1=document.getElementById( 'ctl00_ContentPlaceHolder1_TextBoxpassword ').value;
var p2=document.getElementById( 'ctl00_ContentPlaceHolder1_TextBoxpassword2 ').value;

if(p1!=p2)
{
document.getElementById( 'hint_password ').innerHTML= ' <span style= "color: Red; "> 两次输入不一致 </span> ';
return;
}
if(p1.length <6)
{
document.getElementById( 'hint_password ').innerHTML= ' <span style= "color: Red; "> 密码小于6位数 </span> ';
return;
}

document.getElementById( 'hint_password ').innerHTML= ' <span style= "color: Blue; "> 密码可用 </span> ';
}

</script>

[解决办法]
function username_changed()
{

try{
xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP ");
}catch(e){
try{
xmlhttp = new ActiveXObject( "Msxml2.XMLHTTP ");
}catch(e){
try{
xmlhttp = new XMLHttpRequest();
}catch(e){
xmlhttp = null;
}
}
}
这个就是在创建XmlHttpRequest对象,并且判断是哪种类型的浏览器。
XmlHttpRequest对象主要就是那几种方法。
open()这里面有三个参数“get”就不用提了吧,还有别的可选的,如“post”,而第二个参数就是链接地址了,就是指向问题,第三个参数就是判断是否为异步通信(true).
onreadystatechange() 方法,可以理解为服务器响应后的触发器,就是只要发生通信了就触发他,所以它后面的getReady就是对应的事件了。
function getReady()
{
if(xmlhttp==null)
return;

if(xmlhttp.readyState == 4)
{
if(xmlhttp.status == 200)
{
document.getElementById( 'hint_username ').innerHTML = xmlhttp.responseText;
}
xmlhttp = null;
}
}
这个就是执行了,其中readyState=4 表示请求的状态是完毕,还有其他的状态,但是就4这个状态有用,status 是返回的状态码,200表示请求成功,比如还有什么400阿,之类的自己可以定义。其他的就是JS脚本了。感觉没有什么讲的了。
对了responseText这个是服务器返回的相应字符串。

读书人网 >asp.net

热点推荐