Controller
public function api_students()
{
$students = $this->member->getStudentsPosts();
$new_students = array();
for($i=0; $i<count($students); $i++)
{
$new_students[$i]['student_fullname'] = $students[$i]->student_name.' '.$students[$i]->student_surname.' '.$students[$i]->student_middlename;
$new_students[$i]['student_id'] = $students[$i]->student_id;
$new_students[$i]['student_birth'] = $students[$i]->student_birth;
$new_students[$i]['student_gender'] = $students[$i]->student_gender;
$new_students[$i]['student_addres'] = $students[$i]->student_addres;
$new_students[$i]['student_mobile'] = $students[$i]->student_mobile;
$new_students[$i]['student_email'] = $students[$i]->student_email;
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($new_students));
}
阿贾克斯
$('.students').click(function(){
var student_id = $(this).attr('data-student-id');
$.get(site_url+'/members/api_students/'+ student_id,
function(new_students){
$('#student_name').text(new_students.student_name);
},'json'
);})
问题是,我想从api_students获取信息并通过ajax查看。控制台没有显示任何错误消息,它是空的,所以我不知道要检查什么。我检查了api_students,数据来了,我的ajax代码中有问题
您可以使用
控制器
// get id and send array
public function api_students()
{
$students = $_POST['id'];
/// code
echo json_encode($new_students);
}
阿贾克斯
// send data and use the result
$.ajax({
type: "POST",
url: site_url+'/members/api_students/'+ student_id,
data: 'id='+student_id;
success: function(stud){
// use result array stud
}
});
不是一个完整的答案,但不能把它放在评论中。
据我所知,您的PHP块旨在发送许多学生的详细信息,而不仅仅是一个。如果您在 API 调用中发送student_id,那么您的 PHP 代码肯定应该只为单个学生发送一个 JSON 对象,而不是他们的数组。
如果要发送数组,请更快、更轻松地进行 JSON 块准备...
$new_students = array();
foreach ($students as $s) {
// pre PHP 5.4 use array( instead of [...
$new_students[] = [
'student_fullname' => $s->student_name . ' ' . $s->student_surname . ' '.$s->student_middlename,
'student_id' => $s->student_id,
'student_birth' => $s->student_birth,
'student_gender' => $s->student_gender,
'student_addres' => $s->student_addres,
'student_mobile' => $s->student_mobile,
'student_email' => $s->student_email,
]
}