php - 如何在 jQuery 中获取 Ajax 响应的值
问题描述
我正在使用 ajax 和 Codeigniter,我通过 ajax 向控制器发送请求并得到如下代码的响应:-
控制器响应:-
array(1) {
[0]=>
object(stdClass)#29 (1) {
["absent"]=>
string(1) "4"
}
}
问题就在这里,我怎样才能4
从回复中得到?
阿贾克斯调用: -
$('#staff').change(function(){
let staff_id = $(this).val();
let month = $('#month').val();
$.ajax({
url:base_url+'hr/home/getStaffAbsentDay',
type:'POST',
data:{
'staff_id':staff_id,
'month':month
},
success:function(response){
console.log(response);
}
})
});
控制器:-
public function getStaffAbsentDay(){
$id =$this->input->post('staff_id');
$month=$this->input->post('month');
$this->stuff_model->get_staff_absent_days($id,$month);
}
模型:-
public function get_staff_absent_days($id,$month){
$year =jDateTime::date('Y',false,false,true,'Asia/Kabul');
$this->db->select('absent');
$this->db->from('staff_attendance');
$this->db->where('staf_id', $id);
$this->db->where('year', $year);
$this->db->where('month', $month);
$d=$this->db->get()->result();
return json_encode($d);
}
解决方案
模型:-
public function get_staff_absent_days($id,$month){
$year =jDateTime::date('Y',false,false,true,'Asia/Kabul');
$this->db->select('absent');
$this->db->from('staff_attendance');
$this->db->where('staf_id', $id);
$this->db->where('year', $year);
$this->db->where('month', $month);
$d=$this->db->get()->result();
return $d;
}
控制器功能:-
public function getStaffAbsentDay(){
$id =$this->input->post('staff_id');
$month=$this->input->post('month');
$your_array__data = $this->stuff_model->get_staff_absent_days($id,$month);
echo json_encode($your_array__data);
}
jQuery / Ajax 调用:-
现在你的response
将是一个JS array
而不是一个string
格式。
success:function(response){
var data = JSON.parse(response);
console.log(data[0].absent)
// $('#staffAbsentDays').html('success')
}
推荐阅读
- c++ - 从函数返回 libconfig 类设置对象引用
- javascript - 使用 PHP 将本地存储数据保存到服务器
- php - 如何检查用户是否在 Symfony 中使用 ajax 登录?
- mjml - MJML如何设置编译输出目录与找到的输入文件目录相同?
- bash - 为什么在 bash 3.2 中右侧为空的正则表达式匹配为假,而在 4.2 中为真?
- c# - 在会话中执行命令而不将其传递给每个命令
- spring-boot - java.util.NoSuchElementException:不存在值;Apache cassandra - 春季启动
- react-native - JSON stringify 在 react native 中做了什么
- scala - 如何在scala中将“Wed Apr 10 03:48:00 PDT 2019”转换为 2019-04-10 03:48:00?
- sql - 过滤分区上的行