javascript - json 数据未在 Rails 中传递

标签 javascript ruby-on-rails ajax json ruby-on-rails-4

我正在尝试使用 Rails 4 进行非常简单的 ajax 调用,但未正确检索 json 响应。

这是脚本:

$(document).on "submit", "form[name=upvote-form]", ->
  form = $(this)
  $.post "/vote", $(this).serialize(), (data) ->
    if data["status"] is true
      form.find("input").addClass "disabled"
      $("#vote-count-".concat(form.find("#question_id").attr("value"))).html data["votes"]
    else

    return

  return

alert(data['votes'])未定义,这让我尝试找出问题所在。

然后在控制台中我可以看到:

ArgumentError (Nil location provided. Can't build URI.):
  app/controllers/vote_controller.rb:8:in `vote'

这是有问题的方法:

class VoteController < ApplicationController

    def vote
        question_id = params[:question][:id]
        user_id = current_user.id
        vote = Vote.where(["question_id = :q", { q: question_id }]).where(["user_id = :u", { u: user_id }]).take
        respond_to do |format|
            if vote.nil?
                @vote = Vote.new
                @vote.question = Question.find question_id
                @vote.user = User.find user_id
                @vote.save
                votes = Vote.where(["question_id = :q", { q: question_id }]).count
                format.json { render :json => { status: true, votes: votes } }
            else
                format.json { render :json => { status: false } }
            end
        end
    end
end

知道出了什么问题吗?我能做什么?

最佳答案

respond_with旨在与资源一起使用。示例

def show
  @vote = Vote.find params[:id]
  respond_with(@vote)
end

就您而言,您需要使用 respond_to 方法

def vote
  # stuff
  respond_to do |format|
    if vote.nil?
      # stuff
      format.json { render json: { status: true, votes: votes } }
    else
      # other stuff
    end
  end
end

关于javascript - json 数据未在 Rails 中传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27024807/

相关文章:

javascript - 从中心到底部关闭物化模态

ruby-on-rails - 使用 ransacker 对整数 to_char 进行洗劫

ajax - <h :selectManyCheckbox> with validation on ajax update when INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL is active 的 ClassCastException

javascript - Jquery Ajax加载除某个div之外的整个页面

javascript - Angular.js 应用程序 : eliminate #! 来 self 的单个帖子的 URL,同时保持 slug

javascript - 如何隐藏 jQgrid 中的所有复选框?

ruby-on-rails - 未定义方法 `update' 为 nil :NilClass

javascript - 我如何实现不使用 es6 的react-wavesurfer 实例?

javascript - Web 服务器提供 HTML 页面而不是 JSON

javascript - NGRX/REDUX : update value in deep object by json path