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 (i.e. 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:
tree = <%= raw @node.to_json(:include => :nodes) %>
There be a form with fields corresponding to the properties of Node (name, position, date, etc.). 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.
Clearly I will need java开发者_如何学Goscript to populate the form with the selected node's data. How do I then attach javascript to the <a>
elements to populate the form with the JSON data? For example I could have a recursive partial _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? 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.
Question: Lastly, how can I use AJAX to save objects without using the form? 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. Is it possible to simply POST a json object?
I took the lazy route and skipped down to your question. AJAX has no direct relation to forms. You could just post the JSON object. Use jQuery.post.
精彩评论