Ajax技術實踐之完成Ajax自動完成功能

來源:互聯網
上載者:User
近日學習了一下AJAX,照做了幾個例子,感覺比較新奇。

   第一個就是自動完成的功能即Autocomplete,具體的例子可以在這裡看: http://www.b2c-battery.co.uk

   在Search框內輸入一個產品型號,就可以看見效果了。

   這裡用到了一個開源的代碼: AutoAssist ,有興趣的可以看一下。

   以下為代碼片斷:

index.htm
<script type="text/javascript" src="javascripts/prototype.js"></script>
<script type="text/javascript" src="javascripts/autoassist.js"></script>
<link rel="stylesheet" type="text/css" href="styles/autoassist.css"/>
<div>
<input type="text" name="keyword" id="keyword"/>
<script type="text/javascript">
Event.observe(window, "load", function() {
var aa = new AutoAssist("keyword", function() {
return "forCSV.php?q=" + this.txtBox.value;
});
});
</script>
</div>

    不知道為什麼不能用keywords做文字框的名字,我試了很久,後來還是用keyword,搞得還要修改原代碼。

forCSV.php
<?php
$keyword = $_GET['q'];
$count = 0;
$handle = fopen("products.csv", "r");
while (($data = fgetcsv($handle, 1000)) !== FALSE) {
if (preg_match("/$keyword/i", $data[0])) {
if ($count++ > 10) { break; }
?>
<div on_Select="this.txtBox.value='<?php echo $data[0]; ?>';">
<?php echo $data[0]; ?>
</div>
<?php
}
}
fclose($handle);
if ($count == 0) {
?>
: (, nothing found.
<?php
}
?>

   原來的例子中的CSV檔案是根據\t來分隔的,我們也可以用空格或其它的來分隔,這取決於你的資料結構。

   當然你也可以不讀檔案,改從資料庫裡讀資料,就不再廢話了。

   如下:

轉自81M.net

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.