首頁 > 後端開發 > php教程 > PHP如何通过AJAX方式实现登录功能_PHP

PHP如何通过AJAX方式实现登录功能_PHP

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
發布: 2016-05-29 11:47:49
原創
1157 人瀏覽過

本文实例讲述了Ajax+PHP+MySQL登陆示例。分享给大家供大家参考。具体如下:
运行效果截图如下:

具体代码如下:

1 login.php
登录界面中,javascript脚本用ajax方式异步请求dologin.php,dologin.php负责用户信息验证(包括验证码,php生成验证码可以自行搜索).登录界面的代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

<&#63;php session_start();&#63;>

<!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>login</title>

 <link rel="stylesheet" type="text/css" href="CSS/login.css" />

 <script src="JS/ajaxhelper.js" type="text/javascript"></script>

 <script src="JS/jquery-1.3.2.min.js" type="text/javascript"></script>

 <script type="text/javascript">

  function chkForm() {

   if (m$('username').value == "") {

 

    alert('用户名不能为空.');

    m$('username').focus();

    return false;

 

   }

   if (m$('password').value == "") {

 

    alert('密码不能为空.');

    m$('password').focus();

    return false;

 

   }

   if (m$('password').value != "" && m$('username').value != "") {

 

    var xmlhttp = createRequest();

    if (xmlhttp) {

     m$('loading').innerHTML = "<font color='red'>loading...</font>";

     var username = m$('username').value;

     var pwd = m$('password').value;

     var code = m$('txtCode').value;

     var url = "dologin.php";

     xmlhttp.open("POST", url, true);

     xmlhttp.onreadystatechange = ValidateResult;

     xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

     xmlhttp.send("username=" + escape(username) + "&password=" + escape(pwd) + "&code=" + escape(code));

 

    } else {

     alert('xmlHttp创建失败.');

 

    }

 

    function ValidateResult() {

     if (xmlhttp.readyState == 4) {

      if (xmlhttp.status == 200) {

       if (xmlhttp.responseText != "") {

 

        //window.alert(xmlhttp.responseText);

        var obj = eval("(" + xmlhttp.responseText + ")");

        if (obj.result == true) {

         alert("提示:" + obj.info);

         window.location = 'index.php';

 

        } else {

         alert("错误:" + obj.info);

 

        }

       } else {

        window.alert("从服务器获取失败");

 

        window.location.reload();

       }

       m$('loading').innerHTML = "";

      }

     }

 

    }

 

 

   }

 

  }

 

  function m$(id) {

   return document.getElementById(id);

  }

 

  function changeCode() {

   var xmlhttp = createRequest();

   if (xmlhttp) {

    m$('loading').innerHTML = "<font color='red'>loading...</font>";

    var dt = new Date().getTime();

    // alert(dt);

    var url = "function/imagecode.php&#63;dummay" + escape(dt);

    xmlhttp.open("GET", url, true);

    xmlhttp.onreadystatechange = ValidateResult;

    xmlhttp.send(null);

 

   } else {

    alert('xmlHttp创建失败.');

 

   }

 

   function ValidateResult() {

    if (xmlhttp.readyState == 4) {

     if (xmlhttp.status == 200) {

      var dt = new Date().getTime();

      var url = "function/imagecode.php&#63;dummay" + escape(dt);

      m$('imgCode').src = "function/imagecode.php&#63;dummay" + escape(dt);

      m$('loading').innerHTML = "";

     }

    }

 

   }

  }

 

  function showTool() {

   $('#divToolTip').css("display", "block");

  }

 

  function hideTool() {

   $('#divToolTip').css("display", "none");

  }

  window.onload = initPage;

 

  function initPage() {

   $('#divToolTip').css("display", "none");

  }

 </script>

 </head>

 <body>

 <div style="background-color:#2A3F55; height:80px;">

   

 </div>

 <div style="min-height:500px;">

   

  <div class="left">

   

  <div style="margin:120px auto auto auto; height:300px; text-align:left">

   <div style="font-size:26px;color:#2A3F55; text-align:center;">Ajax PHP Demo System

   <img src="/static/imghw/default1.png"  data-src="Images/appstorm-icon.png"  class="lazy" alt="appcation storm image"   style="max-width:90%"/>

   </div>

   <br/>

   <hr style="border:dashed thin #2A3F55;width:70%; text-align:center;"/>

   <div style="font-size:13px;color:#999999; margin:20px auto 0 auto; padding-left:200px;">

   Author:<a href="#" onmousemove="showTool();" onmouseout="hideTool();">wangming</a>

   </div>

   <div style="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">DateTime:2009-9-1</div>

   <div style="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">Version:1.0.0</div>

   <div style="font-size:13px;color:#999999;margin:20px auto auto auto; padding-left:200px;">Email:wangmingemail@163.com     </div>

   <div id="divToolTip">

   <img  src="/static/imghw/default1.png"  data-src="Images/ming.jpg"  class="lazy" height="86px;"/ alt="PHP如何通过AJAX方式实现登录功能_PHP" >

   <span class="authordes">

    <br/>

    姓名:wangming<br/>

    电商06-2<br/>

   </span>

    

   </div>

    

  </div>

   

  </div>

   

  <div class="right">

   

  <form>

   <br/>

   <table class="flogin">

   <tr>

    <td>用户名:</td>

    <td><input type="text" name="username" id="username"/></td>

    <td></td>

   </tr>

   <tr>

    <td>密   码:</td>

    <td><input type="password" name="password" id="password" /></td>

    <td></td>

   </tr>

   <tr>

    <td>验证码:</td>

    <td>

    <input type="text" name="txtCode" id="txtCode" size="12" />

    <img src="/static/imghw/default1.png"  data-src="function/imagecode.php"  class="lazy" id="imgCode" alt="image code" height="22px;"   style="max-width:90%"/>

    </td>

    <td><input type="button" class="btnrefresh" onclick="changeCode();" /></td>

   </tr>

   <tr>

    <td></td>

    <td><input type="button" class="btnlogin" onclick="chkForm();" /></td>

    <td></td>

   </tr>

   <tr>

    <td></td>

    <td><span id="loading"></span></td>

    <td><span id="code"></span></td>

   </tr>

    

   </table>

  </form>

  </div>

   

 </div>

 <div style="background-color:#2A3F55; height:60px; margin:auto 0 0 0; clear:both; text-align:center; line-height:60px; color:#FFFFFF;font-size:12px;">

  &copy;Copyright 2015.

 </div>

 </body>

</html>

登入後複製

2 ajaxhelper.js

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

function createRequest() {

 try {

  request = new XMLHttpRequest();

 } catch (tryMS) {

  try {

   request = new ActiveXObject("Msxml2.XMLHTTP");

  } catch (otherMS) {

   try {

    request = new ActiveXObject("Microsoft.XMLHTTP");

   } catch (failed) {

    request = null;

   }

  }

 }

 return request;

}

 

function getActivatedObject(e) {

 var obj;

 if (!e) {

  // early version of IE

  obj = window.event.srcElement;

 } else if (e.srcElement) {

  // IE 7 or later

  obj = e.srcElement;

 } else {

  // DOM Level 2 browser

  obj = e.target;

 }

 return obj;

}

 

function addEventHandler(obj, eventName, handler) {

 if (document.attachEvent) {

  obj.attachEvent("on" + eventName, handler);

 } else if (document.addEventListener) {

  obj.addEventListener(eventName, handler, false);

 }

}

登入後複製

3 dologin.php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

<&#63;php

 session_start();

 header("Content-type:text/html;charset=gb2312");//防止返回的中文乱码

 $name=$_POST['username'];

 $pwd=$_POST['password'];

 $imagecode=$_POST['code'];

 if(strtoupper($imagecode)==$_SESSION["code"])

 {

  include("conn/conn.php");

  $sql="select studentName,studentPwd from tbstudent where studentId='".$name."'";

  $result=mysql_query($sql,$conn);

  if($row=mysql_fetch_assoc($result))

  {

   if($pwd==$row['studentPwd'])

   {

   $_SESSION['username']=$row['studentName'];

   //echo "{'result':true,'info':'登陆成功!','code':'".$_SESSION["code"]."'}";

   echo "{'result':true,'info':'登陆成功!'}";

    

   }

   else

   {

   echo "{'result':false,'info':'密码错误!'}";

   }

  }

  else

  {

   echo "{'result':false,'info':'该用户不存在!'}";

  }

 }

 else

 {

  echo "{'result':false,'info':'验证码错误!'}";

 }

&#63;>

登入後複製

4 conn.php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

<&#63;php

 $conn=$mysql_connect("localhost","root", "");

 mysql_select_db("bbs",$conn);

 mysql_query("SET NAMES GB2312");

 &#63;>

 5

 <&#63;php

class Users {

 function Users() {

 }

 function checkLogin($username, $userpwd) {

  try {

   mysql_connect("localhost", "root", "123");

   mysql_select_db("studentdb");

   mysql_query("SET NAMES GB2312");

   $sql = "select userid from tbuser where username='$username' and userpwd='" . md5(trim($userpwd)) . "'";

   $result = mysql_query($sql);

   if ($result) {

    $arr = mysql_fetch_row($result);

    $uid = $arr[0];

    if ($uid != "") {

     return "true|$uid login ok.$sql";

     mysql_close();

    } else {

     return "false|login failed!$sql";

     mysql_close();

    }

   } else {

    return "false|$result link db failed!";

    mysql_close();

   }

  }

  catch(Exception $ex) {

   return "false|$ex";

   mysql_close();

  }

 }

 function AddUser($name, $pwd) {

  try {

   mysql_connect("localhost", "root", "123");

   mysql_select_db("studentdb");

   mysql_query("set names gb2312");

   $sql0 = mysql_query("select userid from tbuser where username='$name'");

   $info0 = mysql_fetch_array($sql0);

   $userid = $info0[0];

   if ($info0 != false) {

    return "false | $name is exisis.(id:$userid)";

   }

   $pwd = md5(trim($pwd));

   $query = mysql_query("insert into tbuser(username,userpwd)values('$name','$pwd')");

   $error = mysql_errno();

   if ($query) {

    return "true | add ok";

   } else {

    return "false | $error";

   }

  }

  catch(Exception $ex) {

   return "false | $ex";

  }

 }

 function DeleteUser($name) {

  mysql_connect("localhost", "root", "123");

  mysql_select_db("studentdb");

  mysql_query("set names gb2312");

  $name = trim($name);

  $sql0 = mysql_query("select userid from tbuser where username='$name'");

  $info0 = mysql_fetch_array($sql0);

  if ($info0 != false) {

   if (mysql_query("delete from tbuser where username='$name'")) {

    return "true | delete ok.(id:" . $info0[0] . ")";

   } else {

    return "false | 删除失败";

   }

  } else {

   return "false | 删除失败 $name 不存在";

  }

 }

 function UpdateUser($id, $name, $pwd) {

  if (is_numeric(intval(trim($id)))) {

   if ($id && $name && $pwd) {

    mysql_connect("localhost", "root", "123");

    mysql_select_db("studentdb");

    mysql_query("set names gb2312");

    $pwd = md5(trim($pwd));

    $isexists = mysql_query("select * from tbuser where userid='$id'");

    if (mysql_fetch_array($isexists)) {

     $sql0 = mysql_query("update tbuser set username='$name',userpwd='$pwd' where userid= $id");

     if ($sql0) {

      return "ture | update ok";

     } else {

      return "false | 更新失败";

     }

    } else {

     return "false | usrid=$id not exists.";

    }

   } else {

    return "false |id=$id name=$name and pwd=$pwd .At least one of them is null.";

   }

  } else {

   return "false | $id is not type of int.";

  }

 }

}

&#63;>

登入後複製

与登录无关,只为了记录一下PHP如何在数据库MYSQL上实现CURD操作.

以上就是告诉了大家PHP如何通过AJAX方式实现登录功能,希望对大家的学习有所帮助。

相關標籤:
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
angular.js - Angularjs $http ajax問題?
來自於 1970-01-01 08:00:00
0
0
0
ajax點擊提交沒反應!
來自於 1970-01-01 08:00:00
0
0
0
javascript - autocomplete ajax怎麼配置,求教
來自於 1970-01-01 08:00:00
0
0
0
ajax 學習需要什麼基礎
來自於 1970-01-01 08:00:00
0
0
0
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板