What does the j function in Rails do?

假如想象 提交于 2019-12-03 05:13:06

escape_javascript(javascript)

Escapes carriage returns and single and double quotes for JavaScript segments.

Also available through the alias j().

From the the rails docs.

Peter actually posted the correct answer. But I will try to elaborate:

I guess you are familiar with the basic concept of ajax? Lets say you want to be able to create comments in an ajaxy fashion. In rails you may respond to POST requests in your CommentsController via:

def create
  @comment = Comment.new(params[:comment])
  respond_to do |format|
    render.js
  end
end

This means if an ajax request from the client (via jquery/javascript) is submitted to the CommentsController it will recognize the format (.js) and respond with the _create.js.erb partial. The partial would then render the new comment with something like this:

$('.comments').append("<%=j render @comment %>");

Now to get to the j or escape_javascript method: Some evil user may submit a comment containing (malicious) javascript which would be executed on your page unless you make use of the j method which

Escapes carriage returns and single and double quotes for JavaScript segments.

and therefore prevents the execution of the code in the browser.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!