首页 > 解决方案 > 如何在 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);
}

标签: phpjqueryjsonajaxcodeigniter

解决方案


模型:-

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')
   }

推荐阅读