使用 Codeigniter Mysql 进行实时搜索

2024-01-05

我正在做一个使用 Jquery Ajax、Php Codeigniter 和 Mysql 进行实时搜索的项目

这是我的模型代码:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Subjectmodel extends CI_Model {
   public function __construct() {
        parent::__construct();

    }
    function getSubject($search){
        $this->db->select("SUB_ID,NAME");
        $whereCondition = array('NAME' =>$search);
        $this->db->where($whereCondition);
        $this->db->from('ix08s_subjects');
        $query = $this->db->get();
        return $query->result();
    }
}
?>

这是我的控制器代码:

<?php
class Subject extends CI_Controller {
    function __construct() {
        parent::__construct();
        $this->load->model('SubjectModel');
    }
    public function index(){
        $search=  $this->input->post('search');
        $query = $this->SubjectModel->getSubject($search);
        echo json_encode ($query);
    }
}
?>

这是我的视图代码:

<html>
<head>
<script type="text/javascript" language="javascript" src="http://somexyz/js/javascripts/plugin/jquery.js"></script>
<script type="text/javascript" src="http://somexyz/js/javascripts/plugin/json2.js"></script>
<script>
    $(document).ready(function(){
      $("#search").keyup(function(){
        if($("#search").val().length>3){
        $.ajax({
            type: "post",
            url: "http://localhost/ibps/index.php/subject",
            cache: false,               
            data:'search='+$("#search").val(),
            success: function(response){
                $('#finalResult').html("");
                var obj = JSON.parse(response);
                if(obj.length>0){
                    try{
                        var items=[];   
                        $.each(obj, function(i,val){                                            
                            items.push($('<li/>').text(val.NAME));
                        }); 
                        $('#finalResult').append.apply($('#finalResult'), items);
                    }catch(e) {     
                        alert('Exception while request..');
                    }       
                }else{
                    $('#finalResult').html($('<li/>').text("No Data Found"));       
                }       

            },
            error: function(){                      
                alert('Error while request..');
            }
        });
        }
        return false;
      });
    });
</script>
</head>
<body>
<div id="container">
<input type="text" name="search" id="search" />
<ul id="finalResult"></ul>
</div>
</body>
</html>

这是我的输出:

[{"SUB_ID":"1","NAME":"物理"},{"SUB_ID":"2","NAME":"物理"}]

但这应该是正确的输出

http://jsfiddle.net/serigo1990/uShzQ/ http://jsfiddle.net/serigo1990/uShzQ/

得到了答案


Add dataType: 'json'到ajax设置

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Codeigniter Mysql 进行实时搜索 的相关文章

随机推荐