当我单击每个按钮的 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/