编写过程分为四步: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;
-
}
-
-
-
}