简体   繁体   中英

Javascript “if statement” and embedded ruby (ruby variable always true)

I have such script inside my html.erb :

if(browser == "Firefox") {
  $(".browser-warning").show();
}

else if(browser == "Safari") {
  if(browser.version < 6) {
    $(".browser-warning").show();
  }
}

else if((BrowserDetect.browser != "Chrome") && (<%= params[:section_id].to_s %> != '')) {
  console.log('yo');
  <%= session[:is_chrome] = false %>
  <%= Rails.logger.debug = "I made is_chrome false, wtf?" %>
}

else {
  $(".browser-warning").show();
}

I'm running this script from Chrome browser and condition returns false .

but session[:is_chrome] is always becomes false and Rails logger returns "I made is_chrome false, wtf?". BUT. JS console logger don't print "yo" in console. Why it's so and what is proper way to define session value only when JS "if" statement is true?

Thanks, all.

On the server while rendering your template every ruby snippet gets evaluated.
So also these lines gets executed on the server (every time, not only if it's not a chrome browser):

<%= session[:is_chrome] = false %>
<%= Rails.logger.debug = "I made is_chrome false, wtf?" %>

To get around this you can do one the following:

  • Check on the server if it's an chrome browser and make the necessary changes
  • Check on the client if it's an chrome browser an make an ajax call to the server to inform that there is an chrome (or non chrome) browser


In addition put <%= params[:section_id].to_s %> in quotes (as user "infused" also stated):

"<%= params[:section_id].to_s %>"

You need to understand that rails is rendering erbs before they are being send to the browser, and there is no erb statements when javascript is running its code. In addition, when rails is rendering the file, it treats everything not surrounded by <% %> as a pure text, so both

<%= session[:is_chrome] = false %>
<%= Rails.logger.debug = "I made is_chrome false, wtf?" %>

are always executed, regardless of what kind of javascript code is written around them.

If you want to execute some server-side code client-side, the only way to do this is to send another request (via Ajax, easy option), or use socketIO to enable client-server communication (never done it by myself :()

However what you're trying to achieve is possible to be achieved strictly on server side: have a look at this question

您需要在Ruby输出中加上引号:

"<%= params[:section_id].to_s %>"

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