利用PHP+JS实现搜索自动提示(实例)
本篇文章对利用PHP+JS实现搜索自动提示的方法进行了详细的分析介绍,需要的朋友参考下
我觉得我有必要写这个教程,因为曾经见到的大部分关于自动完成的应用程序都只是给你一个程序源码包,然后告诉你怎么使用,而不是告诉你它是如何工作的以及为什么这样做。而知道这些可以让你对这个插件可以进一步的按自己的需求定制。
好,我们现在开始。
JavaScript代码 :
复制代码 代码如下:
JS的解释:
好,从上面的代码看到,我们需要连接到一个叫做rpc.php的文件,这个文件处理所有的操作。
lookup函数使用从文本输入框中得到的单词然后使用jQuery中Ajax的方法POST把它传给rpc.php。
如果输入字符 ‘inputString'是‘0'(Zero,译注:在这里是指在搜索框中没输入任何内容),建议框就被隐藏,这也很人性化,你想,如果在搜索框中没有输入任何东西,网站空间,你也不期望会出现个建议提示框。
如果输入框中有内容,我们就得到了这个 ‘inputString'并传递给rpc.php页面,然后jQuery 的$.post()函数被使用,如下:
$.post(url, [data], [callback])
‘callback'部分可以关联一个函数,香港空间,这个比较有意思,只有在数据(data)被加载成功的时候才会执行(译注:此处为意译,没看懂原文:如果返回的数据(data)不为空(也就是说,有东西要显示),那就显示搜索提示框并且使用返回的数据(data)来代替其中的html代码。
就这么简单!
PHP后台程序(rpc.php):
如你所知,网站空间,我的php后台程序都叫做rpc.php(RPC指远程过程调用),而没用它实际执行的功能来命名,但是也还不错了。
复制代码 代码如下:
// PHP5 Implementation - uses MySQLi.
$db = new mysqli(‘localhost', ‘root' ,”, ‘autoComplete');
if(!$db) {
// Show error if we cannot connect.
echo ‘ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST[‘queryString'])) {
$queryString = $_POST[‘queryString'];
// Is the string length greater than 0?
if(strlen($queryString) >0) {
// Run the query: We use LIKE ‘$queryString%'
// The percentage sign is a wild-card, in my example of countries it works like this…
// $queryString = ‘Uni';
// Returned data = ‘United States, United Kindom';
$query = $db->query("SELECT value FROM countries WHERE value LIKE ‘$queryString%' LIMIT 10");
if($query) {
// While there are results loop through them - fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using
// The onClick function fills the textbox with the result.
echo ‘
}
} else {
echo ‘ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo ‘There should be no direct access to this script!';
}
}
?>
PHP代码解释 :
鉴于代码中我已经加了很多注释,在这里我就不再说的很详细了。
一般情况下,需要接收这个 ‘QueryString' 然后在其最后使用通配符产生一个查询语句。
这意味着在这种情况下,每次敲进去一个字符都需要产生一个查询语句,如果一直都这样做的话,恐怕MYSQL会受不了。但是为了尽量的简化这个过程,这种做法对一个规模较小的应用应该没什么问题。
这段php代码你需要在自己的系统中稍作修改,比如你需要更新‘$query'到你自己的数据库,需要看在哪里放你数据库表的列名等等。
CSS样式 :
我使用的是CSS3,天哪,它真的很好用,虽然在Firefox 或者Safari浏览器上会有功能限制。
复制代码 代码如下:
CSS代码都很标准,没什么需要特别指出的。
主文件HTML :
这是主文件的部分html代码,你需要添加的就是一个输入框,并且把 ‘onkeyup' 函数设置为lookup(this.value)。另外,我建议你不要修改它的ID,如果你不想修改上面的Javascript代码的话。
截图 :
我想你应该会想要看看最后的效果是什么样子,OK。
还有,
最后就是有用的链接了,我想你应该期待很久了。
源文件 :点击下载

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
