使用ajax和codeIgniter搜索数据库

时间:2014-09-06 14:33:29

标签: jquery ajax codeigniter search

我wana make search但是我得到了重复的结果,如何删除prev代码表格prev ajax请求我的代码在ajax中是:

<script>
$(function () {


    $("#sample_search").keyup(function () {
        var that = this,
        value = $(this).val();


            $.ajax({
                type: "post",
                url: "<?php echo site_url('home/search')?>",
                data: {
                    'search_keyword' : value
                },
                dataType: "text",
                success: function(msg){
                    //we need to check if the value is the same
                    $("#prostor").append("<p id='rezultati'>"+msg+"</p>");
                }
            });

    });
}); 


</script>

并在php中

 public function search(){
        if(isset($_post['search_keyword'])){

            $var = $_post['search_keyword'];
            $q = $this->db->query("SELECT * from users where username like '%{$var}%'");
            foreach ($q ->result() as $a){
                echo $a->username;
            }

        }
    }

我的问题是如何删除prev搜索结果

2 个答案:

答案 0 :(得分:1)

html()来电中使用append()代替$.ajax,如下所示

success: function(msg){
 //we need to check if the value is the same
 $("#prostor p#rezultati").html(msg);
}

答案 1 :(得分:0)

你有问题在这里:

$("#prostor").append("<p id='rezultati'>"+msg+"</p>");

问题:您反复使用相同的id附加段落,但内容与prostor不同。从一开始就在<p>内设置prostor标记就足够了,然后始终使用text / html更改其.text() / .html()功能