简体   繁体   English

在jQuery中访问Rails参数哈希

[英]Access rails params hash in jquery

Is it possible to access Rails params hash in jquery? 是否可以在jquery中访问Rails params哈希? I need to add one more key(which is nothing but a column in the table) to params before submit of a form. 在提交表单之前,我需要在参数中再添加一个键(表中只有一列)。

$('#form_id').submit(function() {
        // do some manipulation to get key
        params[key] = value;
        // params in rails hash 
        $('#form_id').submit();
 });

Is this possible? 这可能吗?

You can assign the value of a param to a variable in JavaScript, but you'll need to be sure to escape the param to prevent possible XSS attacks. 您可以在JavaScript中将参数的值分配给变量,但是您需要确保转义该参数以防止可能的XSS攻击。

<script>
  var key = "<%= j(params['key']) %>";
</script)>

...but you probably don't need to use JavaScript. ...但是您可能不需要使用JavaScript。 If you're trying to submit one of the params along with the form, you can easily pass it using a hidden form element: 如果您尝试将一个参数与表单一起提交,则可以使用隐藏的form元素轻松传递它:

<input type="hidden" name="column" value="<%= j(params['key']) %>">

This will result in param[:column] being set to the given param value upon form submission. 这将导致在提交表单时将param[:column]设置为给定的param值。

Yes, it's possible. 是的,有可能。

Just add that jQuery code to your template and call params like this. 只需将jQuery代码添加到您的模板中,然后调用参数即可。 I don't know what do you want to do exactly so I just show how to access the params hash. 我不知道您到底想做什么,所以我只说明如何访问params哈希。

Haml version: Haml版本:

:javascript
  console.log "#{j params[:key]}";

ERB version: ERB版本:

console.log "<%= j params[:key] %>";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM