简体   繁体   English

一种形式,很多Model实例:JSON和AJAX(在Rails上)

[英]One form, many Model instances: JSON and AJAX (on Rails)

Background : (If you're lazy but still want to help try just skipping to Question below) I have a model Node with a one to many relationship with itself (ie a tree). 背景 :(如果您很懒,但是仍然想帮助您,请跳到下面的问题)。我有一个模型节点,它与自身(即一棵树)具有一对多的关系。 I would like to have a page where a user can work with the whole tree. 我想要一个页面,用户可以在其中处理整个树。 I will send the tree as a javascript object using JSON: 我将使用JSON将树作为javascript对象发送:

tree = <%= raw @node.to_json(:include => :nodes) %>

There be a form with fields corresponding to the properties of Node (name, position, date, etc.). 表单中包含与Node属性(名称,位置,日期等)相对应的字段。 My question is: what is the best way to build this form so that I can work with all of the above nodes? 我的问题是:构建此表单以便与上述所有节点一起工作的最佳方法是什么?

I will need some sort of widget for selecting a node. 我将需要某种小部件来选择节点。 For simplicity let's say its just a bunch of <a> s. 为了简单起见,我们说它只是一堆<a>

Clearly I will need javascript to populate the form with the selected node's data. 显然,我将需要JavaScript来用所选节点的数据填充表单。 How do I then attach javascript to the <a> elements to populate the form with the JSON data? 然后,如何将javascript附加到<a>元素,以使用JSON数据填充表单? For example I could have a recursive partial _write_node.html.erb: 例如,我可以使用递归的_write_node.html.erb部分:

<a onclick="loadNodeIntoForm("<%=str%>)">node.name</a>
<% for i in 0..node.nodes.size %>
    <%= render :partial => 'write_node', locals => { :node => node.nodes[i], :str => str + '.nodes[' + i.to_s + ']' } %>
<% end %>

that I call using 我用

<%= render :partial => 'write_node', locals => { :node => @node, :str => 'tree.node' } %>

Or perhaps I could use a javascript to build the <a> s on the client side by traversing the tree which would avoid the hackish string concatenation above? 或者,也许我可以使用javascript通过遍历tree来在客户端上构建<a> ,这将避免上面的骇客字符串串联? And I was thinking something like 我在想类似

function loadNodeIntoForm(node) {
    document.getElementById('node[name]').value = node.name;
    document.getElementById('node[date]').value = date.name;
    //etc.
}

Then I will also have javascript that will update the JSON objects when the form is edited. 然后,我还将拥有JavaScript,该JavaScript将在编辑表单时更新JSON对象。

Question: Lastly, how can I use AJAX to save objects without using the form? 问:最后,如何不使用表单就可以使用AJAX保存对象? For example I want the user to be able to edit several nodes before saving so I can't just use ajax on the form, which would only submit the currently edited node. 例如,我希望用户能够在保存之前编辑多个节点,所以我不能只在表单上使用Ajax,而该表单只会提交当前编辑的节点。 Is it possible to simply POST a json object? 是否可以简单地发布一个json对象?

I took the lazy route and skipped down to your question. 我走了懒惰的路线,跳到你的问题。 AJAX has no direct relation to forms. AJAX与表单没有直接关系。 You could just post the JSON object. 您可以发布JSON对象。 Use jQuery.post . 使用jQuery.post

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

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