首页 > 代码库 > Ajax的封装

Ajax的封装

 一次比一次更加简化,提高代码利用率,
技术分享
 1 function ajax() 2 { 3     var xmlHttp=null; 4     if(windows.XMLHttpRequest){ 5         xmlHttp=new XMLHttpRequest(); 6        } 7       else{ 8             if(windows.ActiveXObject){ 9                 xmlHttpReq=new ActiveXObject("Microsoft.XMLHTTP");10             }11         }12        var handler=null;13        this.fun=function(url,mode.synchro,_handler){14             handler=_handler;15             xmlHttp.open(mode,url,synchro);16             xmlHttp.send(null);17         };18         this.callback=function(){19             if(xmlHttp.readyState==4){20                    if(xmlHttp.status==200){21                             handler(xmlHttp.responseText);22                     }else{23                            alert("请求失败");24                      }25             }26 }27 28 function ajaxPost(url,postStr,onsuccess)29 {30     var xmlHttp=window.XMLHttpRequest():new ActiveXObject(‘Microsoft.XMLHttp‘);31     xmlHttp.open("POST",url,true);32     xmlHttp.onreadystatechange=function()33     {34         if(xmlHttp.readyState==4){35                if(xmlHttp.status==200){36                          onsuccess(xmlHttp.responseText);37                   }38                else{39                         alert(‘Ajax服务器返回错误!‘);40                       }41     42               }43 }44       xmlHttp.setRequestHeader(‘Content-Type‘,‘application/x-www-form-urlencoded‘);45       xmlHttp.send(postStr);46 }47                                                 
Ajax的封装
 1 <?php 2     //连接数据库 3     $conn=mysql_connect(‘127.0.0.1‘,‘username‘,‘password‘); 4     if($conn){ 5         mysql_select_db("test",$conn); 6         mysql_query("set names ‘utf-8‘"); 7       } 8     else{ 9            die();10     };11     //用户验证12     $username=$_POST[‘username‘];13     $password=$_POST[‘password‘];14 15     $sql="select * from Users where username=‘$username‘";16     17     $result=mysql_query($sql) or die("用户名不存在");18     $num=mysql_num_rows($result);19     if($num){20         echo 1;21         $_SESSION[‘Z_USERNAME‘]=$username;//保存登录用户22     }else{23         echo 2;24          mysql_close();25     }26 }27 ?>28             
 1 function loginCheck(){ 2     var username=document.getElementById(‘username‘).value; 3     var password=document.getElementById(‘password‘).value; 4     var postStr="username="+username+"&password="+password; 5     if(username==""){ 6             alert("用户名不能为空,请重新输入"); 7              return false; 8     } 9     else if(password==""){10             alert("密码不能为空,请重新输入!");11             return false;12     }13     else{14         ajaxPost("login.php",postStr,function(result){15             if(result=="1"){16                 alert(‘恭喜您,登录成功!‘);17             }18             else if(result=="2"){19                    alert("密码输入有误,请重新输入!");20             }21      });22    }23 }   

 

Ajax的封装