简体   繁体   中英

Rails render JS partial printing code to page

I'm using AJAX in my Rails app to render a JS error message when needed. It was working initially, but now coming back to it some time later, it still shows the JS error message but for some reason it now also prints the entire JS file as HTML in the window . This is what's called in the controller:

respond_to do |format|
  format.js { render :partial => 'error' }
end

My file named _error.js.erb contains some JS which isn't relevant as regardless of what it contains Rails prints it to the window still.

This is what the JS looks like outputted to the window: (I tried commenting out the JS to see if it made a difference)

Imgur

You can try it with some modification :

respond_to do |format|
  format.js
end

Inside the action and in the view action_name.js.erb write your js code ar if you want to put your erb then use escape_javascript.

Check the following link :

Why escape_javascript before rendering a partial?

I did it! In case there will be someone else wondering a few years later, there's the answer: you should put rendered value in a javascript_tag inside your html.erb. Like this:

javascript_tag render: 'error'

that will put what rendered between <script>...</script> tags and escape all unnecessary code.

Here's the documentation on it

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