我正在使用 Jquery Ajax、Php Codeigniter 和 Mysql 进行实时搜索项目
这个搜索类似于
http://w3schools.com/ajax/ajax_aspphp.asp但使用 MYSql
这是我的数据库表:
CREATE TABLE IF NOT EXISTS `ix08s_subjects` (
`SUB_ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(211) DEFAULT NULL,
`added_by` int(11) DEFAULT NULL,
`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`SUB_ID`),
KEY `FK_ix08s_subjects` (`added_by`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='to store the subjects' AUTO_INCREMENT=3 ;
--
-- 为表转储数据ix08s_subjects
INSERT INTO `ix08s_subjects` (`SUB_ID`, `NAME`, `added_by`, `date_added`) VALUES
(1, 'physics', 2, '2013-05-31 10:07:55'),
(2, 'physics', 2, '2013-05-31 10:41:09');
这是我的模型代码-Subjectmodel.php
<?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();
}
}
?>
这是我的控制器代码-Subject.php
<?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);
$this->load->view('search', $query);
}
}
?>
这是我的查看代码 - Search.php
<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(),
dataType: 'json',
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>
每当我在搜索框中输入四个字母时,都会弹出此警报
请求时出错..
没有从数据库中获取值