rails通过js.erb和jquery和ajax传递param变量

时间:2012-12-14 07:00:49

标签: jquery ruby-on-rails ruby-on-rails-3

尝试获取通过params [:hashtag]传递给create.js.erb文件中的AJAX事件的变量。它似乎没有通过,因为它显示空白。它也没有抛出错误。

`$(".swag_text_field").val(<%= escape_javascript(@hashtag_scrubbed) %>)`

create.js.erb

$(".votes-in").html("<%= escape_javascript(render(:partial => 'shared/vote_tweets', :object => @random_hashtags)) %>")
$(".tag-history").html("<%= escape_javascript(render(:partial => 'shared/tag_history', :object => @vote_history)) %>")
$(".leaderboard-tag-history").html("<%= escape_javascript(render(:partial => 'shared/leaderboard', :object => @leaderboard)) %>")
$(".swag_text_field").val(<%= params[:hashtag] %>)
$(".footer-stats").html("<%= escape_javascript(render(:partial => 'shared/stats')) %>")

hashtag_controler.rb

class HashtagsController < ApplicationController

    def cast_vote                                           #Voting in the middle of the page
    Hashtag.cast_vote(params[:cast_vote])                   #Tells which hashtag to vote for
    @vote_history = Hashlog.vote_history                    #updates the vote history on the bottom of the page
    @leaderboard = Hashtag.leaderboard_history_current      #updates the leaderboard on the right
        @cast_vote_hashtag = Hashtag.cast_vote_hashtag(params[:hashtag])
        respond_to do |format|
        format.html { redirect_to root_path }
        format.js
        end
    end 



    def home    
        @vote_history = Hashlog.vote_history
        @leaderboard = Hashtag.leaderboard_history
        # @trends_pull = Trend.trends_pull
        @trends_display = Trend.trends_display
    end

    def create 
        @stats_total = Hashtag.count 
        @stats_wins = Hashtag.sum(:wins)
        @stats_views = Hashtag.sum(:view_count)
        @stats_losers = (@stats_views - @stats_wins) 
        @vote_history = Hashlog.vote_history
        if signed_in?
            Hashtag.create_hashtag_signed_in(params[:hashtag])
        else
            Hashtag.create_hashtag_guest(params[:hashtag])
        end
        Hashlog.create_hashlog(params[:hashtag])
        @random_hashtag_pull = Hashtag.random_hashtags_pull
        @leaderboard = Hashtag.leaderboard_history_current
        respond_to do |format|
            format.html { redirect_to root_path }
            format.js
        end
    end
end

search.html.erb

<%= form_tag hashtags_path, class: "search-form", remote: true do %>
            <div class="input-prepend input-append">
            <span class="add-on swag">#</span>

            <%= text_field_tag :hashtag, nil, onkeypress: "return isNumberKey(event)", class: "span4 swag_text_field", id:"appendedPrependedInput" %>

            <%= submit_tag "VS!", class: "btn add-on-right swag_button" %>
            <% end %>

1 个答案:

答案 0 :(得分:3)

替换$(".swag_text_field").val(<%= params[:hashtag] %>)

$(".swag_text_field").val("<%= params[:hashtag] %>");