我想知道如何在 CodeIgniter 中使用 AJAX 从数据库中获取数据。你能检查下面的代码找出问题的原因吗?在我的 View 中单击链接时没有任何反应。
这是我的看法:
<a href="#" class="faq_title"><?php echo $faq_title; ?></a>
这是我的 Controller :
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")
是一个 anchor 并且 anchor 有文本而不是值。所以我建议你使用 .text()
而不是 .val()
。
关于php - 在 CodeIgniter 中使用 AJAX 从数据库中获取一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23911438/