编写过程分为四步:1、创建ajax对象2、连接服务器,发送请求3、服务器处理4、接受返回值。
一、创建ajax对象
-
function $(id){ -
return document.getElementById(id); -
} -
-
function getXHR(){ -
var oAjax; -
if(window.XMLHttpRequest){ -
//IE7+, Firefox, Chrome, Opera, Safari -
oAjax=newXMLHttpRequest(); -
} -
else{ -
oAjax=newActiveXObject("Microsoft.XMLHTTP") -
}// code for IE6, IE5 -
return oAjax; -
}
二、连接服务器,发送请求
-
var url='/checkName.php?time='+newDate()+'&name='+$('username').value; -
xhr.open('GET',url,true); -
xhr.send(null); -
-
//open(get,url,true) -
//第一个参数:数据传输方式 get post -
//第二个参数:处理文件 xx.php xx.txt ,要数据:直接写路径就好;提交数据:在地址那里写数据(get方式) -
//第三个参数:同步或者异步方式,默认是异步true
-
//send() 如果是get方式,写null或者为空 -
//如果是post,参数那就直接写要传输的内容
三、服务器处理
-
<?php -
-
//3号线:获取ajax传来的信息,做处理,再返回给ajax:后台做,或者后台协作 -
$userName=$_GET['name']; -
-
if($userName=='admin'){//把内容拿到,进行判断,输出信息返回给ajax -
echo'该用户名不能使用'; -
} -
-
else{ -
echo'该用户名能使用'; -
} -
-
?>
四、接受返回值。
-
xhr.onreadystatechange=function(){ -
//alert('现在的状态是:'+xhr.readyState); -
if(xhr.readyState==4){ -
//alert(xhr.responseText); -
$('inf').innerHTML=xhr.responseText; -
} -
-
-
}
-
xhr.onreadystatechange=function(){ -
//alert('现在的状态是:'+xhr.readyState); -
if(xhr.readyState==4){ -
//alert(xhr.responseText); -
$('inf').innerHTML=xhr.responseText; -
} -
-
-
}
本文详细介绍了使用AJAX实现客户端与服务器交互的四个步骤:创建AJAX对象、发送请求、服务器处理及接收响应。通过具体实例展示了如何用JavaScript实现异步数据传输。

7748

被折叠的 条评论
为什么被折叠?



