how to make Javascript alert box display a variable from Rails controller

北城以北 提交于 2019-12-24 01:06:54

问题


I have this piece of Javascript codes in my view file:

<script>
function hint() {
    var str = @user.name;
    var name = str.toLowerCase();

    alert(name);
}
</script>

I want the alert box to display the name of the user so I use the variable @user that was defined in my controller. However, when I click the button to active the alert box, nothing shows up. I also tried current_user.name, but it didn't work either. How can I display the value of a variable in the alert box?


回答1:


Just keep it like this, as like in html file.

 var str = '<%= @user.name %>';



回答2:


You can also do like this:

alert("<%= @user.name.downcase %>");



回答3:


If you have a button then you don't have to write any JavaScript code (assuming a confirmation dialog works for you). You can display a confirmation dialog with data: {confirm: "#{@user.name.downcase}"} passed to your button/submit/link_to helpers:

<%= f.submit 'Save', data: { confirm: "#{@user.name.downcase}" } %>

In addition, it gives you an ability to cancel your button/link click.

Another option without JavaScript is to use onclick event on the button/link:

<%= f.submit 'Save', onclick: "alert('#{@user.name.downcase}');" %>

or pass user name as a parameter to your JavaScript function:

<%= f.submit 'Save', onclick: "your_function('#{@user.name.downcase}');" %>


来源:https://stackoverflow.com/questions/37501281/how-to-make-javascript-alert-box-display-a-variable-from-rails-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!