0

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

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-<%= @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 } %>) 

这是我的html:

         <div class="post_actions" id='post-action-<%= "#{post.id}" %>' >

            <%= render :partial => 'post_voting', :locals => { post: post, user_vote: current_user.votes.where( post_id: post.id ).first } %>

        </div>

这是我的萤火虫控制台输出: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)
4

2 回答 2

0

在弄乱了 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 }) %>");

和木瓜!有用。很高兴解决了这个问题!缩小您的 JQUERY 人员!

于 2012-08-09T15:00:18.867 回答
0

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

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

并将此 ID 添加到您的 html 中的某处。如果这可行,您可以确定 ajax 调用完全执行,而问题只是您引用的 id。

您是否检查过您的 html 源代码中是否存在 id“post-action-2”?

于 2012-08-09T12:49:10.443 回答