đây là đoạn code đơn giản, khi nhập vào ô user nếu user có rồi thì nó sẽ báo(alert) còn không thì không báo, về dữ liệu của user thì TG đặt trong một array trong file .php ( khi viết ứng dụng thì lấy từ data)
code này đơn giản để bạn dễ hiểu, tùy theo yêu cầu mà thêm các xử lý cho phù hợp
gồm 2 file
index.html
<html>
<head>
<title>PHPBASIC - Register with AJAX </title>
</head>
<body>
<script>
function showAlert() { alert('have user');}
function newAlert(url,id)
{
if(document.getElementById)
{
var x=(window.ActiveXObject)?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();
}
if(x)
{
x.onreadystatechange=function()
{
if(x.readyState==4&&x.status==200)
{
if(x.responseText == 1)
showAlert();
}
}
x.open("GET",url,true);x.send(null)
}
}
function check()
{
newAlert('user.php?pba='+document.getElementById('user').value);
}
</script>
<form name="pba_form" method="post" action="">
user:
<input name="user" type="text" id="user" onblur="check();">
<br>
Password:
<input name="pass" type="text" id="pass">
</form>
</body>
</html>
file user.php
<?php
$user_array = array('abc','bac','da','agag');
$user = $_GET['pba'];
if(in_array($user,$user_array)) print 1;
else print 0;
// khi viết thật phần dữ liệu này phải được lấy từ databse
?>
tổng quát của code này:
- khi nhập vào ô user xong, di chuyển dấu nháy sang ô khác(sự kiên onblur) hàm newAlert() đựoc gọi
- hàm newAlert() sẽ truyền giá trị vừa nhập đến file user.php và lấy kết quả trả về từ file user.php, nếu là 1 thì thông báo đã có user, ngược lại thì kô báo
- file user.php làm nhiệm vụ check xem có user trong data chưa, nếu có trả về 1 ngược lại trả về 0
mong rằng ví dụ nhỏ này giúp bạn được một phần nào
Tác giả:NguyÅn Minh Tân
