逃脱字符串 - Ouput rails字符串在Javascript [英] Escape String - Ouput rails string in Javascript

查看:157
本文介绍了逃脱字符串 - Ouput rails字符串在Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图为我的.erb文件中的JavaScript对象分配一个字符串值,如下所示:

So I'm trying to assign a string value to a javascript object in my .erb file like so:

var data = {
    'name': '<%= @product.name %>',
    ...
};

问题是,如果 name 汤姆的小耳朵

输出的 data.name 将是 Tom&#x27; s小耳朵

有没有办法逃脱特殊字符?

Is there a way to escape special characters?

我尝试过'name':'<%= raw @ product.name%>'但是未捕获的SyntaxError:意外的标识符将输出到控制台。

I tried doing 'name': '<%= raw @product.name %>' but Uncaught SyntaxError: Unexpected identifier gets output into the console.

执行<% = escape_javascript @ product.name%> 输出 Tom \&#x27;小耳朵

提前谢谢

修改
@ Stefan在下的评论MrYoshiji的 answer对我有用。

Edit @Stefan's comment under MrYoshiji's answer worked for me.

推荐答案

您可以使用 escape_javascript()完成:

var data = {
    'name': "<%== escape_javascript @product.name %>",
    #...
};

链接:
http://api.rubyonrails.org/classes/ActionView/Helpers/JavaScriptHelper.html#method-i-escape_javascript

此方法的别名是 j

 var data = {
     'name': "<%== j @product.name %>"
 }

这篇关于逃脱字符串 - Ouput rails字符串在Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆