一个简单AJAX范例(用户名检验)

 

#1 创建和填充数据库 ##################################################################
use test;
CREATE TABLE users(
 user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
 username VARCHAR(20) NOT NULL,
 password CHAR(40) NOT NULL,
 first_name VARCHAR(20) NOT NULL,
 last_name VARCHAR(40) NOT NULL,
 email VARCHAR(60) NOT NULL,
 PRIMARY KEY (user_id),
 UNIQUE (username)
);

INSERT INTO users (username, password, first_name, last_name, email) VALUES
 ('sherif', SHA('123456'), 'Seth', 'Bullock', 'seth@address.com'),
 ('Al', SHA('123456'), 'Al', 'Swearengen', 'al@thegem.org'),
 ('Garret', SHA('123456'), 'Alma', 'Garret', 'agarret@address.net');

 


#2 编写PHP脚本 ##################################################################

<?php //checkusername.php

/* This page checks a database to see if
 * $_GET['username'] has already been registered.
 * The page will be called by Javascript.
 * The page returns a simple text message.
 * No HTML is required by this script!
 
*/

 
// validate that the page received $_GET['username']:
 if(isset($_GET['username'])) {

  
// Connect to the database:
  $dbc = @mysqli_connect ('localhost', 'root', 'root', 'test') or die ('The availability of this username will be confirmed upon form submission.');

  
// Define the query:
  $q = sprintf("SELECT user_id FROM users WHERE username='%s'", mysqli_real_escape_string($dbc, trim($_GET['username'])));

  
// Execute the query:
  $r = mysqli_query($dbc, $q);

  
// Report upon the results:
  if(mysqli_num_rows($r)==1) {
   
echo 'The username is unavalibalbe.';
  } 
else {
   
echo 'The username is avalibalbe.';
  }

  
mysqli_close($dbc);

 } 
else { // No username supplied! 
  echo 'Please enter a username.';
 }
?>


#3 编写Javascript ##################################################################

/// checkusername.js

/* This page does all the magic for applying
 * Ajax principles to a registration from.
 * The users's chosen username is sent to a PHP
 * script which will confirm its availability.
 
*/

function GetXmlHttpObject()
{
  
var xmlHttp=null;
  
try {
    
// IE7, Mozilla, Safari, Firefox, Opera, most browsers:
    xmlHttp=new XMLHttpRequest();
    } 
catch (e) { // Older IE browsers
  try {
   xmlHttp
=new ActiveXObject("Msxml2.XMLHTTP");
  } 
catch (e) {
   xmlHttp
=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
 
return xmlHttp;
}

// Function that starts the Ajax process:
function check_username(str) {

 xmlHttp
=GetXmlHttpObject()

 
// Confirm that the object is usable:
 if(xmlHttp!=null) {

  
if (str.length==0){ 
   document.getElementById(
"username_label").innerHTML='Please enter a username.';
   
return;
  }

  
// Call the PHP script.
  // Use the GET method.
  // Pass the username in the URL.
  xmlHttp.open('get''checkusername.php?username=' + encodeURIComponent(str));

  
// Function that handles the response:
  xmlHttp.onreadystatechange = handle_check;

  
// Send the request:
  xmlHttp.send(null);
 } 
else { // can't use Ajax!
  document.getElementById('username_label').innerHTML = 'The availability of this username will be confirmed upon form submission.';
  
return;
 } 

//End of check_username() function.


// Function that handles the response from the PHP script:
function handle_check() {

 
// If everythin's OK:
 if(xmlHttp.readyState == 4){
  
if(xmlHttp.status == 200){ 
   document.getElementById(
'username_label').innerHTML = xmlHttp.responseText;
  }
else{
   document.getElementById(
'username_label').innerHTML = 'The avalilability of this username will be confirmed upon form submitsion.';
  }
 }

//End of handle_check() function.


 表1
------------------------------------------------------------------------
 XMLHttpRequest 属性
------------------------------------------------------------------------
 属性                     包含的内容
------------------------------------------------------------------------
 onreadystatechange       readyState 属性改变是要调用的函数名称
------------------------------------------------------------------------
 readyState               请求的当前状态 (参见表2)
------------------------------------------------------------------------
 responseText             以字符串形式返回的数据
------------------------------------------------------------------------
 responseXML              以XML形式返回的数据
------------------------------------------------------------------------
 status                   返回的HTTP状态代码 (参见表3)
------------------------------------------------------------------------

 

 表2
------------------------------------------------------------------------
 XMLHttpRequest的readyState值
------------------------------------------------------------------------
 值                      含义
------------------------------------------------------------------------
 0                       未初始化
------------------------------------------------------------------------
 1                       正在加载
------------------------------------------------------------------------
 2                       已经加载
------------------------------------------------------------------------
 3                       交互
------------------------------------------------------------------------
 4                       完成
------------------------------------------------------------------------

 

 表3
------------------------------------------------------------------------
 HTTP 常见状态代码
------------------------------------------------------------------------
 代码                   含义
------------------------------------------------------------------------
 200                    正常
------------------------------------------------------------------------
 204                    无内容
------------------------------------------------------------------------
 400                    错误请求
------------------------------------------------------------------------
 401                    未授权
------------------------------------------------------------------------
 403                    禁止
------------------------------------------------------------------------
 404                    没有找到
------------------------------------------------------------------------
 408                    超时
------------------------------------------------------------------------
 500                    内部服务错误
------------------------------------------------------------------------

 

#4 创建HTML ##################################################################

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Registration Form</title>
<script src="ajax.js" type="text/javascript" language="javascript"></script>
<script src="checkusername.js" type="text/javascript" language="javascript"></script>
</head>

<body>
<form action="register.php" method="post">
    
<fieldset>
        
<legend>Registration Form</legend>
        
<p>Username: <input name="username" type="text" size="20" maxlength="20" onchange="check_username(this.form.username.value)" /> <span id="username_label"></span></p>
 
<p>Password: <input name="pass1" type="password" /></p>
 
<p>Confirm Password: <input name="pass2" type="password" /></p>
 
<p>First Name: <input name="first_name" type="text" size="20" maxlength="20" /></p>
 
<p>Last Name: <input name="last_name" type="text" size="20" maxlength="20" /></p>
 
<p>Email Address: <input name="email" type="text" size="20" maxlength="60" /></p>
 
<input name="submit" type="submit" value="Register" />
    
</fieldset
</form
>
</body>
</html>


 表4
------------------------------------------------------------------------
 JavaScript 常见事件
------------------------------------------------------------------------
 事件                         发生时机
------------------------------------------------------------------------
 onfocus                      一个元素获得焦点
------------------------------------------------------------------------
 onblur                       一个元素失去焦点
------------------------------------------------------------------------
 onchange                     一个表单元素的值或状态改变了
------------------------------------------------------------------------
 onreset                      表单被重置
------------------------------------------------------------------------
 onsubmit                     表单被提交
------------------------------------------------------------------------
 onclick                      鼠标点击元素
------------------------------------------------------------------------
 onload                       HTML 页面完成加载
------------------------------------------------------------------------

posted @ 2009-04-02 16:36  独行客  阅读(313)  评论(0编辑  收藏  举报