【问题标题】:Return json response for Ajax request in a basic PHP MVC在基本 PHP MVC 中返回 Ajax 请求的 json 响应
【发布时间】:2012-01-11 02:13:55
【问题描述】:

我计划在 PHP 中为简单项目构建一个轻量级的简单 MVC。

如果是 AJAX 请求,我正在尝试掌握显示视图模板或返回 JSON 响应的简单路径。

下面是我刚想出的一个 sn-p,这都是假设的,所以实际上还没有任何方法存在,这正是我期望它们工作的方式。

查看下面的代码并阅读其中的 cmets,这看起来像您可能会返回 AJAX 请求而不是基本 MVC 中的视图模板吗?

/**
 * 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);
        }
    }

【问题讨论】:

    标签: php model-view-controller


    【解决方案1】:

    我更喜欢你的方法:

    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);
    }
    

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      您的方法看起来非常直观,并且可能非常接近我的做法,但除了我不会使用 JSON 响应每个 AJAX 请求之外。我只会在以下情况下使用 JSON 回复:

      • 在 URI 中请求 JSON(例如 /users/1/json/users/1.json)或
      • JSON 是通过Accepts HTML 标头请求的

      这让您更加灵活/面向未来。如果在将来的某个时刻,您决定要为 AJAX 请求以 XML 格式而不是 JSON 格式提供一些数据,那么您所要做的就是为该请求指定它(例如/users/1.xml)。如果您之前为每个 AJAX 请求提供 JSON,则必须修改所有 AJAX 请求以显式请求 JSON 以适应这一 XML 请求,这对开发人员不是很友好。 :-)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-18
        • 1970-01-01
        • 2013-04-23
        • 1970-01-01
        • 2014-03-12
        • 2016-09-04
        • 1970-01-01
        相关资源
        最近更新 更多