我想知道如何在CodeIgniter中使用AJAX从数据库获取数据。您能否检查下面的代码以找出问题的原因?当我从视图中单击链接时,没有任何反应。
这是我的看法:
<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文件:
$(".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()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句