javascript Rails 中的 j 函数有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12518526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:25:07  来源:igfitidea点击:

What does the j function in Rails do?

javascriptruby-on-railsajaxpartial-views

提问by Tyler DeWitt

I just came across a blog that mentions a jfunction in Rails. They were using it to do ajax style page updates.

我刚刚看到一个博客,其中提到了jRails中的一个函数。他们用它来做 ajax 样式的页面更新。

$('#cart').html("<%=j render @cart %>");

I get they are using partials to render the cartpartial, but whats the point of j? I've found some articles that say it converts the string to something JavaScript will accept, but what does that mean?

我知道他们正在使用部分来渲染cart部分,但有什么意义j呢?我发现一些文章说它将字符串转换为 JavaScript 可以接受的内容,但这意味着什么?

回答by wpp

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 POSTrequests in your CommentsControllervia:

我想你对ajax的基本概念很熟悉吧?假设您希望能够以 ajaxy 方式创建评论。在 Rails 中,您可以通过以下方式响应POST请求CommentsController

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 CommentsControllerit will recognize the format (.js) and respond with the _create.js.erbpartial. The partial would then render the new comment with something like this:

这意味着如果来自客户端的 ajax 请求(通过 jquery/javascript)提交给CommentsController它,它将识别格式 ( .js) 并响应_create.js.erb部分。然后部分将使用以下内容呈现新评论:

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

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

现在转到 j 或 escape_javascript 方法:一些邪恶的用户可能会提交包含(恶意)javascript 的评论,除非您使用该j方法,否则该评论将在您的页面上执行

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

转义 JavaScript 段的回车符和单引号和双引号。

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

从而阻止代码在浏览器中的执行。

回答by Peter Sobot

escape_javascript(javascript)

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

Also available through the alias j().

escape_javascript(javascript)

转义 JavaScript 段的回车符和单引号和双引号。

也可通过别名 j() 获得。

From the the rails docs.

来自rails 文档