Rails escape_javascript creates invalid JSON by escaping single quotes

前端 未结 5 1359
悲&欢浪女
悲&欢浪女 2021-02-07 05:54

The escape_javascript method in ActionView escapes the apostrophe \' as backslash apostrophe \\\', which gives errors when parsing as JSON.

For

5条回答
  •  醉酒成梦
    2021-02-07 06:33

    I had some issues similar to this, where I needed to put Javascript commands at the bottom of a Rails template, which put strings into jQuery.data for later retrieval and use.

    Whenever I had a single-quote in the string I'd get a JavaScript error on loading the page.

    Here is what I did:

    -content_for :extra_javascript do
      :javascript
        $('#parent_#{parent.id}').data("jsonized_children", "#{escape_javascript(parent.jsonized_children)}");
    

提交回复
热议问题