如何在CodeIgniter中使用AJAX从数据库获取数据? [英] How to get data from database using AJAX in CodeIgniter?
本文介绍了如何在CodeIgniter中使用AJAX从数据库获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何使用CodeIgniter中的AJAX从数据库中获取数据.您能否检查下面的代码以找出问题的原因?当我从视图中单击链接时,没有任何反应.
I wonder how to get data from database using AJAX in CodeIgniter. Could you please check the code below to find out the reason of problem? Nothing happens when I click on the link from my view.
这是我的观点:
<a href="#" class="faq_title"><?php echo $faq_title; ?></a>
这是我的控制人:
public function get_faq_data() {
$this->load->model("model_faq");
$title = $_POST['title'];
$data["results"] = $this->model_faq->did_get_faq_data($title);
echo json_encode($data["results"]);
}
这是我的模特:
public function did_get_faq_data($title) {
$this->db->select('*');
$this->db->from('faq');
$this->db->where('faq_title', $title);
$query = $this->db->get('faq');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
这是我的JavaScript文件:
Here is my JavaScript file:
$(".faq_title").click(function() {
var title = $(this).text();
$.ajax({
url: 'faq/get_faq_data',
data: ({ title: title }),
dataType: 'json',
type: 'post',
success: function(data) {
response = jQuery.parseJSON(data);
console.log(response);
}
});
});
推荐答案
尝试一下:
$(function(){ // start of doc ready.
$(".faq_title").click(function(e){
e.preventDefault(); // stops the jump when an anchor clicked.
var title = $(this).text(); // anchors do have text not values.
$.ajax({
url: 'faq/get_faq_data',
data: {'title': title}, // change this to send js object
type: "post",
success: function(data){
//document.write(data); just do not use document.write
console.log(data);
}
});
});
}); // end of doc ready
我所看到的问题是此var title = $(this).val();
,因为您的选择器$(".faq_title")
是锚,并且锚具有文本而不是值.所以我建议您使用.text()
而不是.val()
.
The issue as i see is this var title = $(this).val();
as your selector $(".faq_title")
is an anchor and anchors have text not values. So i suggested you to use .text()
instead of .val()
.
这篇关于如何在CodeIgniter中使用AJAX从数据库获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文