我正在尝试在CI中创建实时搜索功能(我之前从未做过)。我对网络开发很陌生,我还在学习东西。我找到了关于如何做到这一点的小教程http://www.blog.orionwebtech.net/codeigniter-jquery-ajax-live-search/?codekitCB=415037771.748888
我在为我的应用程序翻译该教程中的代码时遇到了问题。我有一个名为属性的表,我希望将输入值与slug列和name列进行比较。然后我希望它返回slug和实时搜索结果中的名称,其中输入值与这些列中的任何一个匹配。它不匹配,因为slug只包含数字,名称包含字母。
这是我提出的尝试执行此操作的代码。
观点:
<div class="something">
<input name="search_data" id="search_data" class="" value="" data-label="Search for a property, a unit, or an resident..." type="text" />
<div id="suggestions">
<div id="suggestionslist">
</div>
</div>
</div>
JavaScript:
<script type="text/javascript">
function ajaxSearch() {
var input_data = $('#search_data').val();
if (input_data.length === 0) {
$('#suggestions').hide();
} else {
var post_data = {
'search_data': input_data,
'<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>'
};
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>search/autocomplete",
data: post_data,
success: function(data) {
// return success
if (data.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').addClass('auto_list');
$('#autoSuggestionsList').html(data);
}
}
});
}
}
</script>
控制器:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Search extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function autocomplete()
{
$search_data = $this->input->post('search_data');
$query = $this->Search_model->get_autocomplete($search_data);
foreach ($query->result() as $row):
echo "<li><a href='" . base_url('association/'.$row->slug) . "'>" . $row->name . "</a></li>";
endforeach;
}
}
/* End of file search.php */
/* File location: application/controllers */
模特:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Search_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function get_autocomplete($search_data)
{
$this->db->select('slug, name');
$this->db->like('slug', $search_data);
$this->db->like('name', $search_data);
return $this->db->get('properties', 10);
}
}
?>
当我测试它时,我没有得到任何结果。我的测试数据有效,因为db中有匹配的行。我做错了什么?
答案 0 :(得分:0)
根据您的链接,您缺少onkeyup=ajaxSearch();
,即
<input name="search_data" id="search_data" class="" value=""
data-label="Search for a property, a unit, or an resident..."
type="text" onkeyup="ajaxSearch();" />
答案 1 :(得分:0)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Search_model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function get_autocomplete($search_data)
{
$this->db->select('slug, name');
$this->db->like('slug', $search_data);
$this->db->like('name', $search_data);
$query = $this->db->get('properties', 10);
return $query->result();
}
}
?>