最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ruby on Rails escape_javascript usage with jQuery - Stack Overflow

programmeradmin2浏览0评论

I have been looking at this Railscast, specifically these lines of code.

// views/reviews/create.js.erb
$("#new_review").before('<div id="flash_notice"><%= escape_javascript(flash.delete(:notice)) %></div>');
$("#reviews_count").html("<%= pluralize(@review.product.reviews.count, 'Review') %>");
$("#reviews").append("<%= escape_javascript(render(:partial => @review)) %>");
$("#new_review")[0].reset();

Could someone explain why escape_javascript has been used for rendering a partial, and displaying a flash notice, but not for the pluralize function?

Thanks

I have been looking at this Railscast, specifically these lines of code.

// views/reviews/create.js.erb
$("#new_review").before('<div id="flash_notice"><%= escape_javascript(flash.delete(:notice)) %></div>');
$("#reviews_count").html("<%= pluralize(@review.product.reviews.count, 'Review') %>");
$("#reviews").append("<%= escape_javascript(render(:partial => @review)) %>");
$("#new_review")[0].reset();

Could someone explain why escape_javascript has been used for rendering a partial, and displaying a flash notice, but not for the pluralize function?

Thanks

Share Improve this question asked Jan 4, 2011 at 14:05 pingupingu 8,82712 gold badges52 silver badges88 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

There are only a couple of possible outputs from pluralize(@review.product.reviews.count, 'Review')

0 Reviews
1 Review
n Reviews

No output of that would ever need to be escaped, so the writer chose not to do so.

Escaping javascript will change <div id="yo">You're Awesome</div> into text that won't cause the javascript interpreter to think the quotes end your string variable.

If you were to type in

var awesome = "<div id="yo">You're Awesome</div>";

It would blow up. The quotes need to be "escaped" into

&lt;div id=\&quot;yo\&quot;&gt;You\'re Awesome&lt;\/div&gt;

You are sending raw javascript response back to browser, which is what jQuery.ajax({type:"script"}) mand expects.

In order to replace the HTML in a page with HTML from AJAX response, it needs to be escaped so it can be sent as javascript; thus the use of escape_javascript.

发布评论

评论列表(0)

  1. 暂无评论