简体   繁体   中英

Can't access JSON data returned from backend

I make an AJAX request and I get back a response saved to a data variable.

My controller:

def retrieve
  data = params[:data]
  @question = Question.find_by(id: params[:question_id])
  @choices = @question.choices
  results = []
  for d in data
    if Choice.find_by(id: d).correct
      results << d
    end
  end

  respond_to do |format|
    format.json {
      render json: {
        choices: @choices.to_json(only: [:id,:correct]),
        results: results,
        message: "success"
        }
      }
  end
end

The response:

Object {choices: "[{"id":1,"correct":true},{"id":2,"correct":false}]", results: Array[1], message: "success"}

I'm getting value undefined where there should be a value.

data.choices[0].id -> returns undefined

Use as_json instead of to_json

Your code should be

@choices.as_json(only: [:id,:correct])

instead of

@choices.to_json(only: [:id,:correct])

For further information about difference between as_json and to_json please checkout this link

Simply as_json works better with complex datatypes like activerecord objects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM