在 CodeIgniter 中使用 AJAX 从数据库中获取单行? [英] Get a single row from the database using AJAX in CodeIgniter?

查看:30
本文介绍了在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆