简体   繁体   English

Rails:如何将JS对象转换为数组参数

[英]Rails: How to turn JS object to array params

I have this JS object: 我有这个JS对象:

obj = {id: 80, attr_name: "avatar", style: "small", upload_path: null} obj = {id:80,attr_name:“头像”,样式:“ small”,upload_path:null}

I then post this object as params with AJAX to the controller. 然后,我将该对象作为带有AJAX的参数发布到控制器。 What I would like to see in the params is something like this: 我想在参数中看到的是这样的:

params[:attachment][:id] = 80
params[:attachment][:attr_name] = "avatar"

and so on and on... 等等等等

So on the JS side I created an object that holds attachment params: 因此,在JS端,我创建了一个保存附件参数的对象:

{attachment:obj}

While I do get params[:attachment] the result it [object Object]. 虽然我确实获得了params [:attachment]的结果,但它还是[object Object]。

How can I turn my JS object into an array inside params[:attachment]? 如何将JS对象转换为params [:attachment]中的数组?

Thanks, 谢谢,

One way is, instead of {attachment: obj} to make it like so: 一种方法是代替{attachment:obj}使其变为:

postData = {
  "attachment[id]": obj.id,
  "attachment[attr_name]": obj.attr_name
}

Another method is to use stringify the JS object as JSON, and JSON.parse it on the other side. 另一种方法是使用将JS对象字符串化为JSON,然后在另一侧使用JSON.parse。

However jQuery.ajax, when you pass an object to the "data" parameter, ought to send it along just fine as is. 但是,当您将对象传递给“数据”参数时,jQuery.ajax应该按原样发送它。 See: Post an object as data using Jquery Ajax 请参阅: 使用Jquery Ajax将对象作为数据发布

Assuming you're using jQuery (which is Rails default), this would work: 假设您使用的是jQuery(Rails的默认设置),则可以使用:

<h1>TEST</h1>

<script type="text/javascript">

  $(function() {

    params = {};
    params.attachment = {};
    params.attachment.id = 80;

    $.post( "/the_action", params, function(data) {
      alert("response");  
    }, "json");

  });

</script>

You may verify this in the controller like this: 您可以像这样在控制器中进行验证:

class MainController < ApplicationController
  respond_to :html, :json
  def index

  end


  def the_action
    print params
    puts params[:attachment][:id]
    render nothing: true
  end

end

That should print the data in the format you desire. 那应该以您想要的格式打印数据。

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

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