3

I have a controller with an action that is being hit remotely, after which my controller_action.js.erb file is run.

Within my controller's action, I am setting a variable @successful = true|false (true|false based on the return value of a function).

Within my javascript file, I want to say if @successful and either alert that the action was successful or alert that it was not.

Any idea how to do this?

4

2 に答える 2

2

try this

<%- if @successful %>
   alert('Blabla');
<%- else %>
   alert('Blabal');
<%- end %>
于 2012-07-10T18:47:19.370 に答える
1

I speak HAML usually, so this might not be exactly correct:

if(<%= @successful %>) {
  // do stuff
} else {
  // do other stuff
}

In HAML, it would be:

:javascript
  if(#{@successful}) {
    // do stuff
  } else {
    // do other stuff
  }

Alternatively, you could do this:

(ERB)

<%- if @successful %>
  // JS code if true
<%- else %>
  // JS code if false
<%- end %>

(HAML)

- if @successful
  :javascript
    // JS code if true
- else
  :javascript
    // JS code if false

The first option will always render all your JS code on the client side, the only difference being if true or false is in the if clause.

The second option will conditionally only render the JS code for the true or false case.

于 2012-07-10T18:40:30.733 に答える