php - 通过ajax jquery从数据库输出数据

标签 php jquery ajax codeigniter

当我单击每个按钮的 ID 时,如何从数据库中获取数据 我的 Controller 功能

public function ajax (){
   $resultdata = $this->Booking_model->roominfo();
   echo json_encode($resultdata);
}

这是我的按钮及其数据室 ID 和类

<button class="bkng bkn-room trans_200" data-room-id ="1">BOOK NOW</button>

这是我的模型

public function roominfo() {
  //if(isset($_POST["id"]))
  //{
        $sql = "Select name, price from rooms WHERE room_id = 'id'";
        $result =  $this->db->query($sql);
        return $result->result_array();
  //}

我的 ajax jquery 及其按钮类和数据室 ID

$(document).ready(function() {
        $(".bkng").on("click", function(event) {
              event.preventDefault(); 
            var id = $(this).data('room-id');
                console.log(id); 
                if(id != '') 
                {
                    $.ajax( {
                    type:"get",
                    url : "Pages/ajax",
                    data:{id:id}, 
                    success:function(data)
                    {
                        alert(data);
                        result = JSON.parse(data); 
                        $('#test1').append(result[0]['name']);
                        $("#test2").append(result[0]['price']);
                        $("#test3").append(result[0]['price']);
                        console.log(data); 
                    }
                });
            } 
            });
        }); 

它总是在控制台错误中显示 Uncaught TypeError: Cannot read property 'name' of undefined

最佳答案

您收到此错误是因为您的查询没有返回任何内容,因为您可能没有 id = 'id' 的房间。因此 JSON.parse 返回此错误。

所以首先您需要修复模型构建有效的查询,例如:

function roominfo() {
    $id=$_POST["id"];
    $query=$this->db->select('name, price')
                    ->where('room_id', $id)
                    ->get('rooms');
    return ($query->num_rows())? $query->result_array():false;  
}   

然后在 ajax 成功后,您可以检查返回的数据: console.dir(data) 而不是使用alert或console.log,因为它们不会向您显示数组结构

您还应该检查是否未返回任何数据(错误):

  type: 'POST',
  success:function(data)
    {
        console.dir(data);
        if (data){
            result = JSON.parse(data); 
            $('#test1').append(result[0]['name']);
            $("#test2").append(result[0]['price']);
        }
        else
        {
            $('#test1').append('no records found']);
        } 
    }

关于php - 通过ajax jquery从数据库输出数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59109199/

相关文章:

没有更新面板的 ASP.NET AJAX

php - jquery 在网页上播放幻灯片的最简单方法

php - 将字段从一个数据库复制到 MySQL 中的另一个数据库

javascript - 为什么这个 setTimeout 方法不起作用?

javascript - 一个按钮——3个应用商店——如何将用户重定向到合适的应用商店?

javascript - 处理二维数组中的 json 响应

php - (PHP) fatal error : Call to a member function bind_param()

php - MySQL 32 位或 64 位 - Apache 32 位 Windows 64 位?

javascript - 使用 jQuery 计算直接子 div 元素

android - Phonegap 本地构建 - jquery ajax 错误 : readystate 0 responsetext status 0 statustext error