【问题标题】:How to fix [object Object] and render from a has many relationship in Javascript?如何修复 [object Object] 并从 Javascript 中的多个关系进行渲染?
【发布时间】: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 的 Adob​​e 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


    【解决方案1】:

    不要尝试在模板文字字符串中做所有事情。 forEach 也对 return 没有任何作用

    尝试类似:

    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> `;
    
      courseHtml += this.students.map(function(student) {
        return `<p>${student.first_name}</p>`;
      }).join('');
    
    
      return courseHtml
    }
    

    【讨论】:

    • 非常感谢...特别是退货部分; )
    猜你喜欢
    • 2019-11-10
    • 1970-01-01
    • 2017-04-23
    • 2023-01-27
    • 2017-08-07
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多