escape_javascript 正在删除尖括号 - 解决方案?
我正在装备 Rails 3 应用程序(版本 3.0.9),以使用 AJAX 和 jQuery 流畅地处理用户帖子。我希望在帖子提交后刷新 #users_info div。我可以让它工作,但 div 的内容无法正确呈现。具体来说,create.js.erb 中的 jquery 代码:
$("#right_bar").html(
'<%= escape_javascript(render :partial => 'shared/user_info') %>'
);
用户信息 div 输出的结果:
<div id=user_info> <h1>
<a href=/users/101>Example Usera> h1>
46 posts <br>
4 discussions <br>
Following 2 topics <br>
Joined 8 days ago.div>
请注意 escape_javascript 函数如何删除 html 中结束标记上的所有前导尖括号(变为 a>、变为 h1>)。如何强制 escape_javascript 避免这样做?我认为这就是所有相关代码,但如果需要,可以发布更多代码。
更新
我想知道使用 to_json 是否可以成为解决方案的一部分。代码:
<%= escape_javascript((render :partial => 'shared/user_info').to_json) %>
结果 html 标签没有被破坏。但是,我不知道如何从 json 转换回来以输出所需的 html。只是觉得这可能是一个正确的开始,但我不知道如何结束它
I am outfitting a rails 3 app (version 3.0.9) to use AJAX and jQuery to fluidly handle user posts. I would like for a #users_info div to be refreshed following the post submission. I can get this to work, but the contents of the div don't render properly. Specifically, the jquery code in create.js.erb:
$("#right_bar").html(
'<%= escape_javascript(render :partial => 'shared/user_info') %>'
);
Results in the user info div outputting:
<div id=user_info> <h1>
<a href=/users/101>Example Usera> h1>
46 posts <br>
4 discussions <br>
Following 2 topics <br>
Joined 8 days ago.div>
Note how the escape_javascript function removes all leading angle brackets on end tags in html ( becomes a>, become h1>). How can I force the escape_javascript to avoid doing so? I think this is all the relevant code, but can post more if needed.
UPDATE
I was wondering if maybe using to_json would be part of the solution. the code:
<%= escape_javascript((render :partial => 'shared/user_info').to_json) %>
results in the html tags not being destroyed. However, i don't know how to convert back from json to output the desired html. Just thought this might be the right start, but i'm not sure how to finish it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我找到了解决方案。只需将 escape_javascript(contents) 的内容包装在 escape_javascript("#{}") 中即可。
我在末尾添加了 html_safe ,这样 Rails 就不会使尖括号变成文字。现在 html 标签可以正确通过,并且所有内容都可以在浏览器中正确呈现。
I found a solution. just wrap the contents of escape_javascript(contents) in escape_javascript("#{}").
I added the html_safe at the end so that rails would not make the angle brackets literal. Now the html tags go through properly, and everything renders properly in the browser.
试试这个:
Try this:
您可能使用的是旧版本的 Rails。六月初的一个版本导致了这个问题。确保升级到您所在分支的当前版本(2.3.12、3.0.9 或 3.1.0.rc4),它应该可以工作。
You're probably on an older version of rails. A release earlier in June caused this problem. Make sure to upgrade to the current release in the branch you're on (2.3.12, 3.0.9, or 3.1.0.rc4) and it should work.