How can I structure/design my web application such that I can reuse code for AJAX/Inline edits. I use MVC (Zend Framework). There are parts that already facilitate reusability
- Views/Layouts - I can disable layout (the "page template" containing
<html><head>
& stuff) jus开发者_JAVA百科t serving the view partial for that action for use in AJAX dialogs - But for Inline edits, I need to serve smaller parts, just the textbox. Furthermore, I need a special action to handle the request (eg.
updateName()
instead ofupdateUser()
)?
What is the way of designing my app to maximize re usability?
You need to use the contextSwitcher
. A quick example
// In side your controller class
public function init()
{
// Obtain the contextSwitcher
$ajaxContext = $this->_helper->getHelper('AjaxContext');
// Add two new contexts, remove which will be JSON and view which will be HTML
$ajaxContext->addActionContext('remove', 'json')
->addActionContext('view', 'html');
// Init the context
$ajaxContext->initContext();
}
You then need to define the two actions remove
and view
remove
is going to return all the view variables in a JSON encoded array which your javascript can parse and use, you therefore do not need a view script. An action using a context like JSON or HTML will automatically have its layout disabled.
public function removeAction()
{
// Do some operations here for removing data, and I'll assume you assign the outcome to $success
if($success)
$this->view->message = "Success";
else
$this->view->message = "There was a problem removing your data";
}
You would access the remove
action by using a URL like /index/remove/format/json
- without the format json the request will fail.
Your HTML action view
will need a view script, here is the action
public function viewAction()
{
// Load something from the database and assign to $data
$this->view->name = $data['name']
}
Your view script will be called view.ajax.phtml
this will contain your output for the view
action, you would access the view action on URL like index/view/format/html
.
The view script may look like this
<h1>Hello <?=$this-escape($this->name)?></h1>
<p>Welcome to my site. This was obtained via an AJAX request.</p>
Remember to read the docs on the contextSwitcher as I may have missed something.
I hope that helps.
精彩评论