rails jquery ajax请求不执行

我正在我正在构建的应用程序上实现一个向上投票系统非常类似于stackoverflow上的应用程序。 当用户点击upvote或downvote时,会向我的一个控制器发送一个ajax请求,他们会更新几个表。 完成后,我使用respond_to路由到执行jquery的js.erb文件来更新用户显示。 但是,jquery没有被执行。 当我舔upvote / downvote时,控制器代码正确执行(我可以在rails控制台中看到它),但用户显示不会更新。 刷新后,用户显示更新,但不是异步。 我知道jquery没有在fire bug控制台中执行b / c我可以看到我的jquery代码 – 它只是没有被应用。 这是我的upvote控制器代码:

def upvote @post = Post.find(params[:id]) @user_vote = current_user.votes.where(post_id: @post.id).first if @user_vote.blank? Vote.create(user_id: current_user.id, post_id: @post.id, vote: 1) @post.upvotes += 1 elsif @user_vote.vote.to_i == 0 @user_vote.vote = 1 @post.upvotes += 1 elsif @user_vote.vote.to_i == 1 return redirect_to :back, :alert => 'You have already upvoted the post' elsif @user_vote.vote.to_i == 2 @user_vote.vote = 1 @post.downvotes -= 1 @post.upvotes += 1 end respond_to do |format| if @post.save and @user_vote.save format.js { } else format.html { redirect_to :back, :alert => 'There was an error in upvoting the post' } end end end 

这是我的upvote.js.erb文件:

 $('#post-action-').html("upvote"); // this normally renders a partial (below), but I am rendering "upvote" until I can fix this // escape_javascript( 'post_voting', :locals => { post: @post, user_vote: @user_vote } %>) 

这是我的HTML:

  <div class="post_actions" id='post-action-' >  'post_voting', :locals => { post: post, user_vote: current_user.votes.where( post_id: post.id ).first } %> 

这是我的firebug控制台输出: http : //i.imgur.com/H6zXJ.png

编辑

我注意到我的服务器出错了:

 Started GET "/assets/bootstrap.js?body=1" for 127.0.0.1 at 2012-08-09 06:33:42 -0700 Served asset /bootstrap.js - 304 Not Modified (0ms) 

你的代码似乎没问题,应该执行。 您可以进行额外检查以更新固定ID而不是计算ID。

 $('#updateme').html("upvote"); 

并在你的html中添加此ID。 如果这样做,你确定ajax-call完全执行,而问题只是你引用的id。

你有没有检查过你的html-source有一个id“post-action-2”?

在弄乱了jquery之后,我注意到了一些事情。 首先,我需要缩小我的代码(取出所有注释和未使用的空格)。 我拿了这个:

 $('#post-action-<%= @post.id %>').html("upvote"); // this normally renders a partial (below), but I am rendering "upvote" until I can fix this // escape_javascript(<%= render :partial => 'post_voting', :locals => { post: @post, user_vote: @user_vote } %>) 

并改为:

 $('#post-action-<%= @post.id %>').html("upvote"); 

然后代码正在运行,用户显示正在更新以显示“upvote”。 完善。 那么我用以下代码替换了上面的代码:

 $('#post-action-<%= "#{@post.id}" %>').html("<%= escape_javascript(render :partial => 'post_voting', :locals => { :post => @post, :user_vote => @user_vote }) %>"); 

和KAPOW! 有用。 很高兴能解决这个问题! 给你的怪人们减肥!