您的位置:首页 > 编程语言 > PHP开发

Ajax与PHP结合实现登录验证

2008-12-03 22:36 459 查看
Step 1:

Create a html file as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>A guide to ajax</title>
<script type="text/javascript" language="javascript">
var xmlHttp=null;
//create the XMLHttpRequest object
function createRequest() {
try {
xmlHttp = new XMLHttpRequest();
} catch (tryMS) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (otherMS) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
xmlHttp = null;
}
}
}
return xmlHttp;
}

//get the querystring
function createQueryString(){
var userId=document.getElementById("userId").value;
var password=document.getElementById("password").value;
var query="userId="+escape(userId)+"&password="+escape(password);
return query;
}
//action
function login(){
createRequest();
var queryString=createQueryString();
var url="login.php?timeStamp="+ new Date().getTime();
xmlHttp.open("post",url,true);
xmlHttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4 ){
if(xmlHttp.status==200)
document.getElementById("result").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.send(queryString);
}
</script>
</head>
<body>
<form action="#">UserId:<input type="text" name="userId"
id="userId" /> Password:<input type="password" name="password"
id="password" /> <br />
<input type="button" onclick="login();" value="login" /></form>
<div id="result"></div>
</body>
</html>

Step 2:

Create a php file:

<?php
//open a connection to database server
$conn = mysql_connect ( "localhost", "root", "admin" );
if (! $conn)
die ( "Connecting to datatabase error:" . mysql_error () );
//select a database
if (! mysql_select_db ( "zry_db", $conn )) {
die ( "Error select the first database:" . mysql_error () );
}
//get the post variablity
$userId = $_POST ["userId"];
$userPwd = $_POST ["password"];
//valid input
if (empty ( $userId )) {
echo "userId required!<br/>";
}
if (empty ( $userPwd )) {
echo "password required!<br/>";
}
//if userId and password not empty
if (! empty ( $userId ) && ! empty ( $userPwd )) {
$sql = "SELECT userId,password FROM login WHERE userId='" . $userId . "' AND password='" . $userPwd . "'";
$result = mysql_query ( $sql, $conn );
if (mysql_num_rows ( $result ) > 0) {
echo "Login Succeed";
} else {
echo "Login Failed";
}
}
//close the connection
@mysql_close ( $conn );
?>
Just so simple!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: