本文讲解如何通过ajax查询mysql数据,并将返回的数据显示在待选列表中,再通过选择最终将选项加入到已选区,可以用在许多后台管理系统中。本文列表框的操作依赖jquery插件。
HTML
<form id="sel_form" action="post.php" method="post"> <p><input type="text" name="keys" id="keys" value="输入姓名或手机号码" onclick="this.value=''" /> <input type="button" id="searchOption" value="搜索" /> <span id="msg_ser"></span></p> <div id="sel"> <select name="liOption[]" id='liOption' multiple='multiple' size='8'> </select> </div> <input type="submit" value="提 交" /> </form>
说明,HTML内容是一个表单,里面放置有一个查询输入框,和一个列表框,以及相关按钮。
MYSQL数据表结构
CREATE TABLE IF NOT EXISTS `t_mult` ( `id` int(11) NOT NULL auto_increment, `username` varchar(32) NOT NULL, `phone` varchar(20) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
表t_mult是一张联系人资料表,包括姓名和手机号码字段。
CSS
<link rel="stylesheet" type="text/css" href="jquery.multiselect2side.css" />
本例中只加载了Multiselect插件所需的样式文件,其他CSS大家可以自行设计。
JAVASCRIPT
首先需要引用本例所需的两个js文件。
<link rel="stylesheet" type="text/css" href="jquery.multiselect2side.css" />
接着我们来调用Multiselect插件。
$("#liOption").multiselect2side({ selectedPosition: 'right', moveOptions: false, labelsx: '待选区', labeldx: '已选区' });
然后我们来写搜索按钮进行Ajax查询数据的操作。
$("#searchOption").click(function(){ var keys=$("#keys").val(); $.ajax({ type: "POST", url: "action.php", data: "title="+keys, success: function(msg){ if(msg==1){ $("#msg_ser").show().html("没有记录!"); }else{ $("#liOptionms2side__sx").html(msg); $("#msg_ser").html(""); } } }); $("#msg_ser").ajaxSend(function(event, request, settings){ $(this).html(""); }); });
说明,当点击搜索按钮时,进行的是Ajax异步操作,JAVASCRIPT将获取的搜索框的输入值,以POST方式传递给后台程序action.php处理,处理后,返回不同的结果给JAVASCRIPT,如果返回1,HTML页面会提示“没有记录”,反之,则将结果输出给左边列表框(待选区):liOptionms2side__sx。注意关键的地方到了,为什么列表框不是XHTML离的liOption,而变成了liOptionms2side__sx了呢?这个要从Multiselect插件说起,Multiselect插件其实就是将一个列表框装换成左右两个列表框,已供相关操作,通过查看其插件代码不难发现,左边的列表框名为:liOptionms2side__sx,右边列表框(已选区)名为:liOptionms2side__dx,后面会用到。
PHP
首先来看action.php的处理。
第一步是连接数据库。
$conn=mysql_connect("localhost","root",""); mysql_select_db("demo",$conn); mysql_query("SET names UTF8");
第二步读取数据,并输出。通过检测搜索框传来的值,构造不同的SQL语句,并将数据返回输出,代码如下:
$keys=trim($_POST['title']); $keys=mysql_real_escape_string($keys,$conn); if(!empty($keys)){ $sql="select * from t_mult where username like '%$keys%' or phone='$keys'"; }else{ $sql="select * from t_mult"; } $query=mysql_query($sql); $count=mysql_num_rows($query); if($count>0){ while($row=mysql_fetch_array($query)){ $str.="<option value='".$row['id']."'>".$row['username']."-".$row['phone']."</option>"; } echo $str; }else{ echo "1"; }
最后还有一个提交操作,后台post.php程序来获取最终提交的项的值。
$selID=$_POST['liOptionms2side__dx']; if(!empty($selID)){ $str=implode(",",$selID); echo $str; }else{ echo "没有选择任何项目!"; }
注意,我们获取的是右边列表框liOptionms2side__dx的值,而不是liOption的值。
一个查询、操作的例子实现了,但是还有一点点瑕疵,在待选区往已选区添加项目时,如何判断控制已经添加过的项目不能重复添加,这个就留给大家思考吧,试一试有什么好的解决方式。

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.


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

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment