如何使用ajax(json)和codeigniter或php显示来自数据库(SQL)的数据?我尝试这样做,但结果是“未定义”,这是我的代码:
jquery代码:
$('[id^="menuitem_"]').on('click',function(){
var menuID = $(this).attr('id').split("_")[1];
$.ajax({
url:"<?php echo base_url();?>Vendors_search/Get_Business_By_Type",
method:"POST",
dataType: "text",
data: {menuID:menuID},
success:function(resp){
var obj = $.parseJSON(resp);
var values = Object.values(obj);
$.each(obj,function(key,val){
$('.business_id').append('<strong>' + val.business_name + '</strong>');
});
}
});
Codeigniter代码:
function Get_Business_By_Type(){
$obj = $this->input->post('menuID');
if($this->Search_obj_model->getBusinessType($obj)){
$bus_type = $this->Search_obj_model->getBusinessType($obj);
$result['business_details'] = $this->Search_obj_model->getBusinessType($obj);
}
else{
$result['message'] = 'Oooops! We could not find your request. Try again later';
}
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($result));
$string = $this->output->get_output();
echo $string;
exit();
}
答案 0 :(得分:2)
执行以下操作以显示JSON数据
在Ajax调用中将dataType
更改为json
无需添加output->set_content_type('application/json')
$result['business_details'] = $this->Search_obj_model->getBusinessType($obj);
}
else{
$result['message'] = 'Oooops! We could not find your request. Try again later';
}
echo $result;
从Ajax获取数据
$.each(resp, function (key, data) {
$.each(data, function (index, data) {
data.business_name // Your Value
});
});