How to pass a javascript variable into a erb code in a js view?(如何在 js 视图中将 javascript 变量传递给 erb 代码?)
问题描述
我的 Rails 3 项目中有这个 Javascript 视图:
I have this Javascript view in my Rails 3 project:
app/views/expenses/new_daily.js.erb
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);
我想通过 locals 将我的 'i' javascript 变量传递给 ruby 部分,我该怎么做?
I want to pass my 'i' javascript variable to a ruby partial through locals, How I can accomplish this?
推荐答案
据我所知没有办法直接做,原因也很简单,html是在服务器端执行,javascript是客户端侧面语言,这意味着它在您的本地浏览器中执行,这就是为什么如果您尝试在两者之间传递一个变量,您将不得不向服务器发出请求,然而,这个问题是通过调用 AJAX 请求来解决的,这个 AJAX 请求与向服务器发送新请求的作用相同,但是它在没有刷新或重新加载页面的情况下这样做会给用户一种没有发出请求的错觉.
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.
一个人问了一个类似的问题 这里
您可以了解更多关于 AJAX 这里在 MDN 上:
这篇关于如何在 js 视图中将 javascript 变量传递给 erb 代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 js 视图中将 javascript 变量传递给 erb 代码?
基础教程推荐
- 在for循环中使用setTimeout 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 动态更新多个选择框 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01