如何在 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 上:
相关文章