如何在ThinkPHP项目中利用ajax实现一个搜索功能

本篇文章为大家展示了如何在ThinkPHP项目中利用ajax实现一个搜索功能,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

具体实现方法如下:

后台代码:

复制代码 代码如下:

//搜索,如果在1不在0 
function search(){ 
    $keyword = $_POST['search']; 
    $Goods=M('goods'); 
  //这里我做的一个模糊查询到名字或者对应的id,主要目的因为我这个系统是 
  //商城系统里面用到直接看产品ID 
    $map['goods_id|goods_name']  = array('like','%'.$keyword.'%'); 
    // 把查询条件传入查询方法 
    if($goods=$Goods->where($map)->select()) 
     { 
              $this->ajaxReturn($goods,'查询成功!',1); 
     }else{ 
              $this->ajaxReturn($data,"查询失败,数据不存在!",0); 
 } 
}


前端代码:

复制代码 代码如下:

$(document).ready(function(){ 
   $(".show_message").hide(); 
   var $search=$('#search_box'); 
   $("#submit_from").click(function(){ 
    if($("#search_box").attr("value")=='') 
    { 
        //alert('请输入文字!'); 
        $(".show_message").html('错误提示:搜索框文本不能为空!'); 
        $(".show_message").fadeIn(1000); 
        $(".show_message").fadeOut(1000); 
        $search.focus(); 
        //return false; 
    }else{ 
        //开始ajax执行数据 
        $.ajax({ 
            type: "POST", 
            url:"/index.php/Goods/search", 
            data:{ 
                search:$search.val() 
            }, 
            dataType: "json", 
            success: function (data) { 
    if (data.status == 1) { 
            //alert(data.info); 
            var html=''; 
                    $.each(data.data,function(no,items){     
                    html+=''; 
                    }); 
                    html+=" 
'+items.goods_id+' '+items.goods_name+' '+items.add_time+' '+items.brand+' '+items.price+'";     
                     $(".goods-list").html(' ').html(html); 
                   // alert(html); 
    } 
    else if (data.status == 0) { 
        $(".show_message").show(); 
        $(".show_message").html(data.info); 
                    $(".show_message").fadeOut(3000); 
    //    alert(data.info); 
          return false; 
        } 
      } 
         }); 
    } 
  }); 
});

上述内容就是如何在ThinkPHP项目中利用ajax实现一个搜索功能,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。