php+ajax实时获取下拉数据程序代码
你点击需要的数据后,这个数据写如到当前输入框,并在后面添加逗号隔开,继续输入的时候,后台处理继续输出数据以供选择.
下面我们来看实例,html代码如下:
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- ajax实时获取下拉数据</pre>
- <style><!--
- .input_s{ position:relative}
- .input_s ul{ list-style:none; margin:0; padding:0; width:200px; border:1px solid #ccc; border-bottom:none}
- .input_s ul li{ border-bottom:1px solid #ccc}
- .input_s ul li:hover{ color:#fff; background:#000}
- --></style>
- <pre></pre>
- <div class="input_s"><input class="tla" id="tla" style="width: 500px;" type="text" name="tla" />
- </div>
- <pre>
- <script type="text/javascript">
- var funjieliu = function(fn, delay){
- var timer = null;
- return function(){
- var context = this, args = arguments;
- clearTimeout(timer);
- timer = setTimeout(function(){
- fn.apply(context, args);
- }, delay);
- };
- };
- document.getElementById("tla").onkeyup=funjieliu(function(){
- var tla = $("#tla").val();
- if(tla){
- $.post("/cityosweb/default.php/shanmao/input_xiala",{tla:tla},function(data){
- if(data.status==1){
- $(".inul").html("");
- $.each(data.data,function(index,val){
- $(".inul").append("
- <li>"+val.username+"</li>
-
- ");
- });
- }
- },"json");
- }
- },500);
- $(function(){
- $(".inul li").live("click",function(){
- var thval = $(this).html();
- var tla = $("#tla").val();
- var regexp = new RegExp(",");
- if(regexp.test(tla)){
- $("#tla").val(tla+thval+",");
- }else{
- $("#tla").val(thval+",");
- }
- $(".inul").html("");
- $("#tla").focus();
- });
- });
-
PHP代码如下:
- function input_xiala(){
- $input = new input();
- $tval = $input->post('tla');
- $u = M('User');
- if(strpos($tval,",")){
- $val = explode(",",$tval);
- $tval = end($val);
- }
- $re = $u->field('username,email')->where("username like '$tval%'")->limit(10)->select();
- $this->ajaxReturn($re,'success',1);
- }