How to make AJAX integration easier
How it might work:
- A page is rendered
- Some AJAX action is triggered, e.g. by clicking on "Edit" to display a form
- An AJAX GET request is sent to a view and JSON returned
- The JSON response contains some HTML snippets which get rendered
- The JSON response might contain some javascript function names which are then executed e.g. for initializing the form (e.g. TinyMCE)
Now the form gets filled out and submitted. Here we have the following scenario:
#. The form is submitted via AJAX POST #. An JSON response is returned (probably) #. The JSON response might contain two things: either the form has some errors to display or the form was ok and the content is displayed again #. The JSON response again contains a list of HTML snippets and a list of JS functions to call.
A JSON response in general can look like this:
{
html :
{id1 : 'contents for id1',
id2 : 'contents for id2',
},
js : ['jsfunc1', 'jsfunc2', ...],
}
So how could an edit view look like? It needs to define the following things:
- A function for rendering a form or in general various HTML snippets which can be global. It also needs to know which JS functions to call
- A list of JS functions to be included in the header
- A definition of which JSON response needs to be sent
Questions
- How does the view know about what else needs updating? E.g. the actions could be replaced as well and the edit view shouldn't know about that logic.
- Can we use some sort of profile? A profile defines a set of parts which need to be rerendered under a certain context. A context can be defined as "content x, edit form shown". That means that the main page just is transformed to that profile. Maybe it can be seen as variant.
- Transfering from one profile to another might depend on the state before. Like an edit view might need some saving during it's transformation to a view.
- Parts which make up a profile should either be renderable via AJAX or embeddable in a page.
- Maybe the transformation logic like data saving should be out of scope for the profile switching. Also what happens in case of a form error?
- Maybe the controller should control the page and tell it what to show. So in fact we might have view but this only resides on the client side and the controller sends out commands to change it.
Example edit view
class EditView(object):
def _setup(self, settings):
"""here we define things which need to be included in the head for this view. It is only called once per application"""
settings['jsfuncs'].add(jsfunc1 = jsfunc1_data, jsfunc2 = jsfunc2_data, ...)
def show_form(self, context):
"""display the form via AJAX"""
form = get_form(context)