我计划在PHP中为简单项目构建一个轻量级的简单MVC。
我试图掌握一个简单的方法,如果是AJAX请求,可以显示View模板或返回JSON响应。
下面是我刚刚想到的一个片段,它都是假设的,所以还没有一个方法真正存在,这只是我希望它们工作的方式。
看看下面的代码并阅读其中的注释,这看起来像是在基本MVC中返回AJAX请求而不是视图模板的方式吗?
/**
* Example Controller
*/
class Test_Controller extends Core_Controller {
function SomeAction($userId)
{
//GET ID from URI
$this->request->get($userId['id']);
// load a Model 'some' = Model Name
$this->profile_model = $this->loadModel('some');
// Get the Dataset from the Model
$profileData = $this->profile_model->getProfile($userId);
// Check if this is an AJAX request true/false
if($this->request->isAjax()){
//is AJAX is true then we return json instead of loading a View template
return $this->response->json($profileData);
}else{
// load view file
$this->view->load('userProfile', $profileData);
}
}
在您的方法中,我更喜欢这种方式:
public function executeSomeAction($request)
{
if ($request->isXmlHttpRequest())
{
$this->actAsJsonResponse(); // here you set headers and other things
/**
* $code - 0, if all's fine, other on error
* $message - verbal message that describe the error, or success
* $extra - any data to send.
*/
return $this->prepareJsonResponse($code, $message, $extra);
}
}
因此,在我的框架中,我有这样的东西:
public function executeSave('Lighty'Request'Request $request)
{
$this->actAsJsonResponse();
$p = 'Lighty'Model'ParticipantSqlAdapter::getInstance()->findById($this->getUser()->getIdParticipant());
$data = $request->get('profile', 'Lighty'Request'Request::POST, array());
if (count($data))
{
$form = new 'Form'Profile(array(
'default' => array_merge($p->getAccount()->getArray(), $p->getArray(), $data),
));
if ($form->save($p))
{
if (isset($data['tags']))
{
$tags = explode(',', $data['tags']);
array_trim($tags);
$tags = array_unique($tags);
$data['tags'] = implode(', ', $tags);
unset($tags);
}
$this->prepareMetaResponse(0, 'Your profile saved successfully', array('updated' => $data));
}
else
{
$this->prepareMetaResponse(1, 'Passed data is invalid', array('error' => $form->getErrors()));
}
}
else
{
$this->prepareMetaResponse(2, 'Not enough data passed');
}
}
然后简化客户端的处理请求:
if (response.code == 0) {
// do whatever you need to, on success
} else {
alert(response.code + ' ' + response.message);
}
希望能有所帮助。
您的方法看起来非常直观,可能非常接近我的做法,但例外的是,我不会用JSON响应每个AJAX请求。我只会在以下情况下使用JSON进行响应:
- 在URI中请求JSON(例如
/users/1/json
或/users/1.json
),或者 - JSON是通过
Accepts
HTML标头请求的
这使您能够更加灵活/经得起未来考验。如果在将来的某个时刻,您决定要以XML格式而不是JSON为AJAX请求提供一些数据,那么您所要做的就是为该请求指定它(例如/users/1.xml
)。如果您以前为每个AJAX请求提供JSON,则必须修改所有AJAX请求以显式请求JSON,以适应这一个XML请求,这对开发人员来说不是很友好。:-)