【发布时间】:2019-07-27 13:26:03
【问题描述】:
我正在使用 Ajax 制作一个展示页面,其中我有一个由课程讲师呈现的教育课程,但在尝试设置该特定课程的学生时我得到 [object Object]。我想为课程渲染所有学生。
我尝试将学生作为属性添加到课程序列化程序中。
class CourseSerializer < ActiveModel::Serializer
attributes :id, :name, :instructor, :students
has_many :ratings
has_many :students, through: :ratings
end
这是我的点击事件。
$(document).on('click','.show_link',function(e) {
e.preventDefault()
$('.ajaxStyling').html('')
let id = $(this).attr('data-id')
fetch(`/courses/${id}.json`)
.then(res => res.json())
.then(course => {
let newCourse = new Course(course)
let courseHtml = newCourse.formatShow()
$('.ajaxStyling').append(courseHtml)
})
})
构造函数。
function Course(course) {
this.id = course.id
this.name = course.name
this.instructor = course.instructor
this.students = course.students
}
原型函数。
Course.prototype.formatShow = function () {
let courseHtml = `
<a href="/courses/${this.id}" data-id="${this.id}"><h3 class="showText">${this.name} by ${this.instructor}</h3></a>
${this.students}.forEach(function(student) {
return "<p>" + student.first_name + "</p>"
})
`
return courseHtml
}
但我在页面中收到以下错误。
这呈现为按预期工作的链接 --> Adam Greco 的 Adobe Analytics 201
但以下是不对的。上面链接下方页面中呈现的代码-->
[object Object],[object Object],[object Object].forEach(function(student) {
return "" + student.first_name + "" })
这是我的网络请求中的数据。
{id: 6, name: "Adobe Analytics 201", instructor: "Adam Greco",…}
id: 6
instructor: "Adam Greco"
name: "Adobe Analytics 201"
ratings: [{id: 29, rating: 2, course_id: 6, student_id: 11, created_at: "2019-05-23T00:54:22.813Z",…},…]
students: [{id: 11, first_name: "Stefan", last_name: "Candelaria"}]
0: {id: 11, first_name: "Stefan", last_name: "Candelaria"}
1: {id: 12, first_name: "Robby", last_name: "Pasurin"}
2: {id: 10, first_name: "Rafa", last_name: "Lopez"}
【问题讨论】:
标签: javascript arrays json oop serialization