I'm new in the world of JavaScript, jQuery, and Ajax. I have a JavaScript function where I want to use the value of a JavaScript variable inside of embedded Ruby code. For example, below I want to use the JS p variable as an argument to the Ruby call to @r.search():

我是JavaScript、jQuery和Ajax领域的新手。我有一个JavaScript函数,我想要在嵌入的Ruby代码中使用一个JavaScript变量的值。例如,下面我想使用JS p变量作为对Ruby调用to @r.search()的参数:

$(function (){
  $('#data-select').on('change',function (){
     var p = document.getElementById('data-select').value; 
     alert(<% j @r.search(+ p +) %>);
  });
});

I want to know if i can do this? And if i can what's the syntax?

我想知道我能不能做到?如果我能,语法是什么?

2 个解决方案

#1


4

First off, I'm assuming this is Ruby on Rails (which you tagged it as). When using ERB you are telling Rails to first evaluate the embedded Ruby code to dynamically insert data that is on the server-side, and then send the file to the client over the internet where their web browser then evaluates the JavaScript.

首先,我假设这是Ruby on Rails(您将其标记为)。在使用ERB时,您要告诉Rails首先评估嵌入的Ruby代码,以动态插入服务器端上的数据,然后通过internet将文件发送给客户端,然后由他们的web浏览器评估JavaScript。

So if this is what's in your file, and you passed a @user variable with a name method that evaluates to "John Smith":

因此,如果这是文件中的内容,您传递了一个@user变量,并使用一个name方法计算为“John Smith”:

// test.js.erb
alert("Hello <%= @user.name %>");

When that file is rendered, your server will evaluate it to this:

当该文件被呈现时,您的服务器将对其进行评估:

// test.js
alert("Hello John Smith");

And then send that over the internet to the client. Only once the client's computer has received this file will the JavaScript be evaluated. They (and the JavaScript) will therefore never see the embedded Ruby code. Therefore what you're doing cannot be done the way you have it because the Ruby code is evaluated before the JavaScript can set the p variable.

然后通过互联网发送给客户。只有客户机的计算机接收到这个文件,才能对JavaScript进行评估。因此,他们(以及JavaScript)将永远看不到嵌入的Ruby代码。因此,您所做的事情不能按照现有的方式进行,因为Ruby代码是在JavaScript可以设置p变量之前进行评估的。

If you want to get information that resides on the server after the client has received the file and is running the JavaScript, you can use something called Ajax, which uses JavaScript to send data asynchronously back to the server. Check out this Rails guide for more details on that.

如果希望在客户端收到文件并正在运行JavaScript之后获得驻留在服务器上的信息,可以使用Ajax,它使用JavaScript将数据异步发送回服务器。查看这个Rails指南,了解更多细节。

更多相关文章

  1. Jquery 只执行一次的代码
  2. Jquery禁用/启用按钮与文本框代码
  3. 推荐web 前端代码的编辑分享平台——RunJS
  4. 想要改进我的jQuery代码,做我想要的,太丑了,IMO
  5. JQuery的一些基本功能代码(CH1&2)
  6. 如何让代码等待好/取消按钮选择?
  7. 如何在angularjs代码中单元测试jquery元素
  8. jquery常用代码片段
  9. Webhoster插入了一个javascript,它会阻止我的代码如何删除它?

随机推荐

  1. 3、android颜色取值
  2. Android添加横线和竖线分割界面
  3. Android开机分析
  4. Android官方资料--Adoptable Storage
  5. android dialog style属性设置
  6. 关于android的monkey测试
  7. Android Pid和Uid
  8. Android(安卓)ANR
  9. Android内存泄漏调试教程
  10. android stackView