我正在使用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>
如果我在搜索框中键入四个字母,我会弹出此警告
请求时出错..
未从数据库中获取值
答案 0 :(得分:1)
问题在于返回格式为http://localhost/ibps/index.php/subject
。
您已添加以下行:
$this->load->view('search', $query);
与您之前的问题“Live search using Codeigniter Mysql”相比较。这可能是在输出中添加了一个html模板,而不是ajax调用所期望的json
。