我正在尝试使用 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/