MVC: how to ajax?

前端 未结 6 817
我在风中等你
我在风中等你 2021-02-03 14:01

I\'m going to start a project using a Zend Framework MVC implementation.

How do I work with ajax? I mean, should I place all ajax code into controller? Or into view?

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-03 14:35

    My syntax might be older but this a sketch of my REST action from my Index Controller:

    /**
     * REST Action for this application.
     *
     * @return void
     */
    public function restAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
    
        $parameters = (func_num_args() > 0) ? array($key => func_get_arg(0)) : $this->getRequest()->getParams();
    
        $key = 'restCommand';
        if(!array_key_exists($key, $parameters)) throw new Exception('Request for “' . $key . '” not found.');
        $restCommand = $parameters[$key];
    
        $xmlString = IndexModel::getEmptyXmlSet($restCommand);
        $xslFile = IndexModel::getModelFilePath('index');
    
        //Handle OPML-driven REST commands:
        if(stripos($restCommand, 'opml-') === 0)
        {
            $opmlCall = explode('-', $restCommand);
            if(count($opmlCall) != 3)
            {
                $xmlString = Songhay_SimpleXml::getXmlMessage('OPML Call Not Recognized', array('The number of parameters are incorrect.'));
            }
            else
            {
                $opmlSet = $opmlCall[1];
                $opmlId = $opmlCall[2];
                $xmlString = IndexModel::getRssFragmentWithOpml($opmlSet, $opmlId);
            }
        }
    
        //Handle general REST commands:
        switch($restCommand)
        {
            case 'deeplink':
                $key = 'id';
                if(!array_key_exists($key, $parameters)) throw new Exception('Request for “' . $key . '” not found.');
                $url = $parameters[$key];
                $xmlString = IndexModel::getRssFragment($url);
                $xmlString = Songhay_SimpleXml::loadXslString($restCommand, $xmlString, $xslFile);
                break;
            case 'index':
                $opmlFile = IndexModel::getModelFilePath('index', '.xml');
                $xmlString = Songhay_SimpleXml::loadXmlAndStripNamespaces($opmlFile);
                $xmlString = Songhay_SimpleXml::loadXslString($restCommand, $xmlString, $xslFile);
                break;
            default:
                $xmlString = Songhay_SimpleXml::loadXslString($restCommand, $xmlString, $xslFile);
        }
    
        $response = $this->getResponse();
        $response->setHeader('Content-Type', 'text/xml');
        $response->setBody($xmlString);
    
        return;
    }
    

提交回复
热议问题