Tạo ứng dụng suggestion đơn giản dùng Ajax Để giải quyết vấn đề nhanh chóng và hiệu quả, mình sẻ tóm gọn cách thức trình bày theo quy tắc - ít nhất người đọc bài nầy cũng đã hiểu được th
Trang 1Tạo ứng dụng suggestion đơn giản dùng Ajax
Để giải quyết vấn đề nhanh chóng và hiệu quả, mình sẻ tóm gọn cách thức trình bày theo quy tắc - ít nhất người đọc bài nầy cũng đã hiểu được thế nào là AJAX và cách deploy một ứng dụng của nó như thế nào
Đầu tiên ta sẻ tạo một form HTML như sau:
<form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form> <p>Suggestions: <span id="txtHint"></span></p>
Ở đây chúng ta có một ô nhập txt1 và được cài sự kiện onkeyup Sự kiện nầysẻ gọi hàm showHint(thamsố) và tham số truyền vào sẻ là giá trị của ô nhập
và đây là code của hàm showHint()
function showHint(str)
{
if (str.length==0)
Trang 2{
document.getElementById("txtHint").innerHTML=""; return;
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="gethint.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
Hàm được thực thi mỗi khi có 1 kí tự được nhập vào ô txt1
Trang 3Nếu có kí tự (str.length > 0) hàm sẻ thực thi:
Định nghĩa url (filename) gửi tới server
Thêm một tham số (q) vào url với nội dung là giá trị của ô txt1 (thực chất
là công việc ghép chuỗi để tạo một request url gửi lên server)
Thêm một sô ngẫu nhiên để tránh không server tạo cache
Tạo một đối tượng XMLHTTP , và gán một hàm thực thi stateChanged
Mở đối tượng XMLHTTP với url
Gửi HTTP request tới server
Nếu ô txt1 rỗng thì hàm nầy sẻ xóa nội dung của txtHint
Đoạn code trên gọi 1 hàm GetXmlHttpObject()
Mục đích của hàm nầy là giải quyết vấn đề tạo ra đối tượng XMLHTTP trên các trình duyệt khác nhau:
function GetXmlHttpObject()
{
var xmlHttp=null;
Trang 4try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
}
return xmlHttp;
}
Trang 5Hàm stateChanged() như sau:
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText; }
}
Hàm nầy được thực thi mỗi khi trạng thái của đối tượng XMLHTTP thay đổi
Khi trạng thái có giá trị là 4 ("complete") thì nội dung của txtHint sẻ được gán bằng response text
Bây giờ, tổng hợp chúng ta có 1 trang HTML hoàn chỉnh như sau:
Trang 6<html>
<head>
<script src="/trung-tam-tin-hoc/clienthint.js"></script>
</head>
<body> <form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form> <p>Suggestions: <span id="txtHint"></span></p> </body>
</html>
và nội dung của file clienthint.js như sau:
var xmlHttp
function showHint(str)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
Trang 7xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="gethint.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText; }
Trang 8}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
Trang 9}
}
return xmlHttp;
}
Tiếp theo chúng ta cần xây dựng Ajax phía server Bạn có thể dùng bất kỳ ngôn ngữ server-side nào tùy thích Bài này trình bày cho bạn 2 ngôn ngữ khá
là phổ biến: ASP và PHP
AJAX ASP
Trang "gethint.asp" được viết bằng VBScript và chạy trên Internet Information Server (IIS):
<%
response.expires=-1
dim a(30)
'Fill up array with names
a(1)="Anna"
a(2)="Brittany"
Trang 10a(3)="Cinderella" a(4)="Diana" a(5)="Eva"
a(6)="Fiona" a(7)="Gunda" a(8)="Hege" a(9)="Inga"
a(10)="Johanna" a(11)="Kitty" a(12)="Linda" a(13)="Nina" a(14)="Ophelia" a(15)="Petunia" a(16)="Amanda" a(17)="Raquel" a(18)="Cindy" a(19)="Doris" a(20)="Eve" a(21)="Evita" a(22)="Sunniva"
Trang 11a(23)="Tove"
a(24)="Unni"
a(25)="Violet"
a(26)="Liza"
a(27)="Elizabeth"
a(28)="Ellen"
a(29)="Wenche"
a(30)="Vicky" 'get the q parameter from URL
q=ucase(request.querystring("q")) 'lookup all hints from array if length of q>0
if len(q)>0 then
hint=""
for i=1 to 30
if q=ucase(mid(a(i),1,len(q))) then
if hint="" then
hint=a(i)
else
hint=hint & " , " & a(i)
end if
end if
next
Trang 12end if 'Output "no suggestion" if no hint were found
'or output the correct values
if hint="" then
response.write("no suggestion")
else
response.write(hint)
end if
%>
AJAX PHP
Chú ý: bạn phải thay đổi giá trị của biến url trong file "clienthint.js" từ
"gethint.asp" thành "gethint.php"
<?php
header("Cache-Control: no-cache, must-revalidate");
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
// Fill up array with names
$a[]="Anna";
Trang 13$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
Trang 14$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky"; //get the q parameter from URL
$q=$_GET["q"]; //lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)))) {
if ($hint=="")
{
$hint=$a[$i];
Trang 15}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found // or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
Trang 16//output the response echo $response;
?>