PHP+jQuery实现自动补全功能源码
前面手工写了一个下拉自动补全功能,写的简单,只实现了鼠标选择的功能,不支持键盘选择。由于项目很多地方要用到这个功能,所以需要用心做一下。发现select2这个插件的功能可以满足当前需求。
在使用jquery插件select2的过程中遇到了一些疑惑,无论是穿json数据还是通过jsonp方式取数据,都能够正确返回。可是下拉列表中的条目却不能被选中,对鼠标和键盘选择都无效。
后来发现,select2插件在实现选中时是以数据中的id字段为准的。所以不管是json还是jsonp,ajax返回的数据都必须拥有id字段。如果实际数据库中不存在这样的id,也可以人为构造一个,但是要保证id的唯一性。
这里列出模板文件try_diy.tpl的源码:
其中colum输入框是插件作用的地方,但其返回的值是id,当页面提交后我们需要把用户选择的版块重新呈现给用户,我的做法是根据表单提交的id查询对应的版面名称name,当控制器收到id值且非空的时候,把版块id对应的名称name值同时呈现到页面上显示出来。由于select2插件是把name名称放在构造的
复制代码 代码如下:
<script> <BR>$(document).ready(function() { <BR>$('#colum').select2({ <BR>minimumInputLength: 0, <BR>placeholder: '选择版块', <BR>ajax: { <BR>url: "http://pm.feiliu.com/?c=try&a=ajax_diy",<SPAN style="BACKGROUND-COLOR: #f5f5f5; COLOR: #008000">//<SPAN style="BACKGROUND-COLOR: #f5f5f5; COLOR: #008000"> 提供jsonp请求的url地址 <BR> dataType: 'jsonp', <BR> jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名(一般默认为:callback,故可省略) <BR> //jsonpCallback:"testback", <BR> //jsonpCallback是自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可写"?",jQuery会自动处理数据 <BR>quietMillis: 100, <BR>data: function(name, page) { <BR>return { <BR>types: ["exercise"], <BR>limit: -1, <BR>q: name <BR>}; <BR>}, <BR>results: function(data, page ) { <BR>return { results: data.items } <BR>} <BR>}, <BR>formatResult: function(exercise) { <BR>return "<div class='select2-user-result'>" + exercise.name + ""; <BR>}, <BR>formatSelection: function(exercise) { <BR>return exercise.name; <BR>} <BR>}); <br><br>$('#colum').change(function(){ <BR>frm.submit(); <BR>}); <BR>var name = $("#columname").val(); <BR>if(name){ <BR>$("#s2id_colum").find("span").text(name); <BR>} <BR>}); <BR></script>
下面是控制器的例子:
复制代码 代码如下:
class pmc_try
{
public function diy(){
if($_POST['colum'])
{
$fid = $_POST['colum'];
$fname = mod_forum::get_forum_name_by_fid($fid);//根据id取name
pm_tpl::assign('frmid',$fid);
pm_tpl::assign('frmname',$fname);
pm_tpl::display("try_diy");
}else
{
pm_tpl::display("try_diy");
}
}
public function ajax_diy(){
$fid = $_GET['q'];
$callback = $_GET["callback"]; //默认函数名为callback
$forums = mod_forum::get_ajx_forum_by_tpid($fid);
$total = count($forums);
$result = array(
'total'=>$total,
'items'=>$forums
);
$output = json_encode($result);
echo $callback.'('.$output.')';//构造jonsp
exit();
}
}
?>
model方法:
复制代码 代码如下:
public static function get_forum_name_by_fid($fid)
{
$sql = "SELECT name FROM sq_forums WHERE fid='$fid' ORDER BY threads_counter DESC";
$data = pm_db11::result_first($sql);
return $data;
}
public static function get_ajx_forum_by_tpid($tpid, $fid)
{
//产品ID:tpid,版块ID:fid
$data = array();
if($tpid && $fid){//构造一个id字段,也可以通过对查询结果加工构造
$sql = "SELECT fid AS id,fid,name FROM sq_forums WHERE tpid='$tpid' AND name LIKE N'%$fid%' ORDER BY threads_counter DESC";
$query = pm_db11::query($sql);
$data = pm_db11::fetch_all($query);
}
return $data;
}
补充一下,实际使用为突出提示效果,可以高亮显示name中包含的查询关键字,这一点可以再select2的formatResult函数中处理,也可以在php中进行加工处理。这一点 的源码我这里就不写了。
补充参考http://www.cnblogs.com/dowinning/archive/2012/04/19/json-jsonp-jquery.html

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



The hard disk serial number is an important identifier of the hard disk and is usually used to uniquely identify the hard disk and identify the hardware. In some cases, we may need to query the hard drive serial number, such as when installing an operating system, finding the correct device driver, or performing hard drive repairs. This article will introduce some simple methods to help you check the hard drive serial number. Method 1: Use Windows Command Prompt to open the command prompt. In Windows system, press Win+R keys, enter "cmd" and press Enter key to open the command

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

If you are using a Linux operating system and want the system to automatically mount the drive on boot, you can do this by adding the device's unique identifier (UID) and mount point path to the fstab configuration file. fstab is a file system table file located in the /etc directory. It contains information about the file systems that need to be mounted when the system starts. By editing the fstab file, you can ensure that the required drives are loaded correctly every time the system starts, thus ensuring stable system operation. Automatically mounting drivers can be conveniently used in a variety of situations. For example, I plan to back up my system to an external storage device. To achieve automation, ensure that the device remains connected to the system, even at startup. Likewise, many applications will directly

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

Preface: vim is a powerful text editing tool, which is very popular on Linux. Recently, I encountered a strange problem when using vim on another server: when I copied and pasted a locally written script into a blank file on the server, automatic indentation occurred. To use a simple example, the script I wrote locally is as follows: aaabbbcccddd. When I copy the above content and paste it into a blank file on the server, what I get is: aabbbcccddd. Obviously, this is what vim does automatically for us. Format indentation. However, this automatic is a bit unintelligent. Record the solution here. Solution: Set the .vimrc configuration file in our home directory, new
