繁体   English   中英

Rails jQuery Ajax请求未执行

[英]rails jquery ajax request not executing

我正在与我在stackoverflow上构建的应用程序非常相似的应用程序上实施投票系统。 当用户单击upvote或downvote时,一个ajax请求将发送到我的一个控制器,他们将更新几个表。 完成此操作后,我将使用response_to路由到执行jQuery以更新用户显示的js.erb文件。 但是,没有被执行的jQuery的。 当我点击upvote / downvote时,控制器代码会正确执行(我可以在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>

这是我的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调用可以完全执行,而问题只是您要引用的id。

您是否检查过html源中是否存在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! 有用。 很高兴解决了这个问题! 最小化您的JQUERY人!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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