简体   繁体   中英

Rails 4: Passing a variable from controller to javascript

I'm new to Rails and have been confused by this problem for a while.

I'm looking to create a translation app. When a user clicks a link containing a word, I want the rails controller to get the translation through an external API call, save the word and translation, and then display the translation, all without refreshing the page.

The particular issue I have is getting some string (which will be the translation) to be passed from the controller to a js file, where it can then update the HTML to display the translation.

In the controller (texts_controller.rb):

def createword
    @word = Word.new(word_params)
    @word.save
    @translation = "Some string"
    respond_to do |format|
         format.js
    end
end

In the javascript (createword.js.erb)

console.log("done");
$(".message").html(<%= @translation %>);

When I delete the second line containing @translation, the javascript works just fine and logs "done" to the console. However, when I do include that line, none of it works.

How can I get this variable to the js, or if that is not possible, what is the best way to get it to the view?

我没有尝试过,但是添加一些引号可能会满足您的要求:

$(".message").text("<%= @translation %>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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