[英]How to get the value of Ajax response in jQuery
我正在使用 ajax 和 Codeigniter,我通过 ajax 向控制器发送请求并得到如下代码的响应:-
控制器响应:-
array(1) {
[0]=>
object(stdClass)#29 (1) {
["absent"]=>
string(1) "4"
}
}
问题是我怎样才能从响应中得到4
?
ajax调用:-
$('#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')
}
看起来您的 PHP 正在使用var_dump
输出其数据。 这是一个 PHP 调试工具。 不要用它来编写 API!
使用标准格式输出数据:
header("Content-Type: application/json");
echo json_encode($your_data);
然后response
将是一个 JS 数组而不是一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.