如何将 javascript 变量传递到 js 视图中的 erb 代码中?

发布于 2024-10-17 03:11:39 字数 423 浏览 4 评论 0原文

我的 Rails 3 项目中有这个 Javascript 视图:

app/views/expenses/new_daily.js.erb

var i = parseInt($('#daily').attr('data-num')) + 1;
//$('#daily').append('agrego fila ' + i + ' <br />');

$('#daily').append('<%= escape_javascript(render(partial: 'new_expense', locals: { i: i })) %>');

$('#daily').attr('data-num', i);

我想通过局部变量将我的 'i' javascript 变量传递给 ruby​​ 部分,我怎样才能完成这个?

I have this Javascript view in my Rails 3 project:

app/views/expenses/new_daily.js.erb

var i = parseInt($('#daily').attr('data-num')) + 1;
//$('#daily').append('agrego fila ' + i + ' <br />');

$('#daily').append('<%= escape_javascript(render(partial: 'new_expense', locals: { i: i })) %>');

$('#daily').attr('data-num', i);

I want to pass my 'i' javascript variable to a ruby partial through locals, How I can accomplish this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

与之呼应 2024-10-24 03:11:40

以下是有关如何执行此操作的一些不同选项:

http:// jing.io/t/pass-javascript-variables-to-rails-controller.html

Here's a few different options on how to do it:

http://jing.io/t/pass-javascript-variables-to-rails-controller.html

无法回应 2024-10-24 03:11:40

这里最好的其他答案是正确的,这不能通过将 javascript 变量传递到 erb 部分来完成,因为它是在服务器上呈现的,而不是在客户端上呈现的。

但由于任何寻找此问题的人可能都对解决方案感兴趣,而我在这里没有看到该解决方案,因此我将发布这个与 Rails UJS 和 Turbolinks 配合良好的示例。

首先,您将控制器设置为以 HTML 形式返回部分:

format.html { render partial: "new_expense" }

接下来,在 app/views/expenses/new_daily.js.erb 中编写一个 javascript AJAX 函数:

var i = parseInt($('#daily').attr('data-num')) + 1;

$.ajax({
  url: '/daily',
  type: 'GET',
  dataType: 'html',
  contentType: "application/html",
  success: function(response) { 

      $('#daily').replaceWith(response)

      $('#daily').attr('data-num', i);
  }
});

这将使您的 Rails 部分返回为一个 html 片段,可用于替换渲染页面的该部分。您可以使用 jQuery 获取 data-num 属性值,对其进行一些数学运算,替换视图中的部分内容,然后再次设置属性值。

您可能会问为什么要费尽心思获取 Rails 部分并将其替换到页面上,而不是仅仅获取数据属性,对其进行数学计算并进行设置?答案是,这是最好的,也许是唯一的方法,当使用 UJS 渲染 Rails 部分并处理对操作的异步响应时,这是非常重要的。

如果您在 create.js.erb 模板中处理来自服务器的异步响应,那么您的变量(例如@daily)将不会反映请求完成后完成的工作(例如,如果在 Sidekiq 等后台服务器上进行了处理)。在这种情况下,您没有最新的操作响应变量可以传递到 js.erb 文件中的 Rails 部分,但您也无法传递 javascript data< /code> 响应您的部分内容,如本问题所指出的。

据我所知,这种方法是在收到异步响应(未显示)的响应后获得完全最新的部分的唯一方法。这将为您提供最新的部分,允许您将 JavaScript 放入其中,并且足够灵活,可以在几乎任何用例中工作。

The best other answers here are right that this can't be done by passing the javascript variable into an erb partial, since it is rendered on the server, not the client.

But since anyone looking for this is probably interested in a work-around solution, which I don't see here, I will post this example that works well with Rails UJS and Turbolinks.

First, you set up your controller to return a partial as HTML:

format.html { render partial: "new_expense" }

Next, write a javascript AJAX function in app/views/expenses/new_daily.js.erb:

var i = parseInt($('#daily').attr('data-num')) + 1;

$.ajax({
  url: '/daily',
  type: 'GET',
  dataType: 'html',
  contentType: "application/html",
  success: function(response) { 

      $('#daily').replaceWith(response)

      $('#daily').attr('data-num', i);
  }
});

This is going to get your Rails partial as an html fragment that you can use to replace that part of your rendered page. You can use jQuery to get your data-num attribute value, do some math on it, replace the partial in your view, and then set the attribute value again.

You may ask why go to all the trouble of getting the Rails partial and replace it on the page, instead of just getting the data attribute, doing math on it, and setting that? The answer is that this is the best, and perhaps the only way of doing something which is really essential when rendering a Rails partial using UJS while handling an asynchronous response to an action.

If you are handling an asynchronous response from your server in a create.js.erb template, then your variables (@daily, for example) are not going to reflect the work done after the request has completed (for example, if there has been processing on a background server like Sidekiq). In that case you don't have up-to-date action response variables to pass into your Rails partial in the js.erb file, but you also can't pass the javascript data response into your partial, as pointed out in this question.

As far as I know, this approach is the only way to get a fully up-to-date partial after receiving a response to an asynchronous response (not shown). This get you the up-to-date partial, allows you to get your javascript into it, and is flexible enough to work in pretty much any use case.

做个ˇ局外人 2024-10-24 03:11:40

让我们确保我们互相理解。您的 erb 模板 (new_daily.js.erb) 将在服务器端处理,将评估 ruby​​ 代码(在 <% %> 内),进行替换,然后生成的 javascript 将被发送到浏览器。然后,在客户端,浏览器将评估此 JavaScript 代码,并为变量 i 分配一个值。
现在你想什么时候传递这个变量以及传递给哪个部分?

Let's make shure we understand each other. Your erb template (new_daily.js.erb) will be processed on the server side, ruby code will be evaluated (within <% %>), substitution made, and then resulting javascript will be sent to browser. On the client side the browser will then evaluate this javascript code and variable i will be assigned a value.
Now when do you want to pass this variable and to what partial?

深巷少女 2024-10-24 03:11:39

据我所知,没有办法直接做到这一点,原因也很简单,html是在服务器端执行的,而javascript是一种客户端语言,这意味着它在本地浏览器中执行,这就是为什么如果你尝试要在两者之间传递变量,您必须向服务器发出请求,
然而,这个问题是通过调用 AJAX 请求来解决的,这个 AJAX 请求的作用与向服务器发送新请求相同,但是它在不刷新或重新加载页面的情况下做到了这一点,给用户带来了没有发出请求的错觉。

有人问了类似的问题在这里

您可以了解有关 AJAX 的更多信息MDN 上

As far as i know there is no way to do it directly and the reason is fairly simple too, html is executed at the server side and javascript is a client side language which means its executed in your local browser, thats why if you even try to pass a variable between the two you'll have to make a request to the server,
However this problem is tackled by calling an AJAX request, this AJAX request does the same thing as sending a new request to the server however it does that without refreshing or reloading the page to it gives the users the illusion that no request was made.

a guy asks a similar question Here

and you can learn more about AJAX Here on MDN:

╰つ倒转 2024-10-24 03:11:39

是的,您可以使用 jquery 传递值;

<%=f.text_field :email ,:id=>"email_field" %>

<script type="text/javascript">
   var my_email= "[email protected]"
   $(document).ready(function(){
        $("#email_field").val(my_email);
   });
</script>

Yes you can pass the value by using jquery;

<%=f.text_field :email ,:id=>"email_field" %>

<script type="text/javascript">
   var my_email= "[email protected]"
   $(document).ready(function(){
        $("#email_field").val(my_email);
   });
</script>
彩扇题诗 2024-10-24 03:11:39

简单的答案是你不能。部分在服务器端扩展,JavaScript 变量稍后在客户端设置。您可以将 i (作为变量名)作为部分的参数并在那里使用它。

render :partial => 'xx', :locals => { :variable => 'i' }

并且在部分

alert(<%= variable %>);

Simple answer is you can't. Partials are expanded at server side, and JavaScript variables are set later at client side. You could make i (as a variable name) a parameter of the partial and use it there.

render :partial => 'xx', :locals => { :variable => 'i' }

And in partial

alert(<%= variable %>);
七分※倦醒 2024-10-24 03:11:39

看看 gon 宝石。 https://github.com/gazay/gon

它为您提供了一个简单的对象,您可以将变量传递给该对象将通过 window.gon 可用于您的脚本

也可在此处引用
http://railscasts.com/episodes/324-passing-data-to-javascript

Check out the gon gem. https://github.com/gazay/gon

It gives you a simple object you can pass variables to that will be available to your scripts via window.gon

Also referenced here
http://railscasts.com/episodes/324-passing-data-to-javascript

困倦 2024-10-24 03:11:39

1) 您可以在 erb 模板中创建一个带有全局变量的 js 标签,之后您将能够从任何 js 文件访问该变量

<%= javascript_tag do %>
   window.productsURL = '<%= j products_url %>';
<% end %>

2) 您可以将数据传递给 erb 模板中的 data-attribute 并通过客户端上的 js 访问它那边 $('#products').data('products')

<%= content_tag "div", id: "products", data: {products: Product.limit(10)} do %>
   Loading products...
<% end %>

3) 您可以使用 gon,在 js 中使用 Rails 变量

有一篇很好的文章,请阅读它,并针对您的具体情况提供良好的解决方案
http://railscasts.com/episodes/324-passing-data-to-javascript ,
更多评论在这里 http://railscasts.com/episodes/324 -将数据传递给javascript?view=asciicast

1) You may create a js tag with global variable in you erb template, after that you will be able to access that variable from any js file

<%= javascript_tag do %>
   window.productsURL = '<%= j products_url %>';
<% end %>

2) You can pass data to data-attribute in erb template and access it by js on client side that way $('#products').data('products')

<%= content_tag "div", id: "products", data: {products: Product.limit(10)} do %>
   Loading products...
<% end %>

3) You can use gon, to use your Rails variables in your js

There is a good article, read it and fine solution for your specific case
http://railscasts.com/episodes/324-passing-data-to-javascript,
more comments are here http://railscasts.com/episodes/324-passing-data-to-javascript?view=asciicast

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文