简体   繁体   中英

Rails variables not working in JavaScript code

In one of my Rails partials, in which I have access to the Folder model, some JavaScript is strangely enough not working. The Folder model has instances of the Submission model which belong to it. Example JSON for a folder instance looks like this:

{"created_at":"2013-09-24T18:55:54Z","id":2,"parent_id":null,"title":"Tumblr Drafts","updated_at":"2013-09-24T18:55:54Z","user_id":1,
"submissions":
[{"content":"This is a test.","created_at":"2013-09-30T23:00:00Z","folder_id":2,"id":93,"parent_id":null,"title":null,"updated_at":"2013-09-30T23:00:00Z","user_id":1}],"children":[]}

As you can see, the submissions are included in the JSON. The controller action looks like this:

    def show
        respond_to do |format|
            format.html
            format.js
            format.json {render :json => @folder.as_json( :include => [:submissions, :children])}
        end
    end

However, when I try to run this JavaScript, it doesn't return a console.log:

<script type="text/javascript">
      var wordCount = 0;
      <% @folder.submissions.each do |submission| %>
        var words = <%= submission.content %>.split(' ');
        wordCount += words.length;
      <% end %>
      console.log(wordCount);
    </script>

I use the @folder variable everywhere else in the partial in question, and it works. I can even output the titles of all the submissions into <p> tags. Is it may because the content field can be left empty, so sometimes it returns null?

Your problem is right here:

var words = <%= submission.content %>.split(' ');

That will dump your submission.content value into your JavaScript without any quoting so you'll end up saying things like:

var words = blah blah blah.split(' ');

and that's not valid JavaScript. You need to quote that string and properly escape it:

// You may or may not want submission.content HTML encoded so
// you might want submission.content.html_safe instead.
var words = '<%=j submission.content %>'.split(' ');

Or better, just do it all in Ruby rather than sending a bunch of throw-away text to the browser:

<script type="text/javascript">
  var wordCount = <% @folder.submissions.map { |s| submission.content.split.length }.sum %>
  console.log(wordCount);
</script>

That assumes that your JavaScript .split(' ') is really intended to split on /\\s+/ rather than just single spaces of course.

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