MVC: как к ajax?

Если Вы устанавливаете расширение панели инструментов веб-разработчика, существует опция под "Источником Представления", названным "Представление Сгенерированный Источник", который покажет Вам текущий источник страницы, включая любые изменения DOM, которые Вы, возможно, внесли.

7
задан Valentin Golev 30 September 2009 в 16:55
поделиться

6 ответов

You really should read the manual chapter about ContextSwitch Action Helper. But here is a brief outline:

  • your view scripts (action-name.phtml) are used for regular HTML output
  • you can initialize a context switch for some actions in the controller so thay can output for example XML - xml context is supported by default and you would put your view script for xml context in (action-name.xml.phtml); xml context also disables rendering of the layout
  • json is also supported by the built in context switch and default option is to disable both the layout and the view and to output all the variables assigned to the view from the controller action in JSON format, this option can be toggled by using the setAutoJsonSerialization(false) method of the context switch; but if you switch it you have to create a view script action-name.json.phtml and output the variables in JSON format by hand

To switch between these two contexts you have to add a format parameter to your URL, e.g. /posts/author/ivan/format/json or /posts/author/ivan/format/xml. If you do not specify the format your application will output plain html.

Special version of the Context switch is AjaxContext and you also have to configure this one by hand. It does not use the 'format' parameter to identify which format it should use for output but it examines the header sent in your request and looks for 'X-Requested-With: XmlHttpRequest' header and if it is present the AjaxContext is examined. Using the AjaxContext action helper you can specify which context should be used for specific actions if the request is fired using AJAX.

13
ответ дан 6 December 2019 в 07:27
поделиться

Взгляните на AjaxContext Action-Helper (или на ContextSwitch, который он расширяет), и он позволит вам использовать точно такой же код контроллера, переключаясь на отдельный view-script (foo.json.phtml или foo.ajax.phtml и т. д. - автоматически выбирается из параметра формата?) или используйте JSON Action-Helper, который вернет объект, содержащий все переменные, которые вы назначаете представление - так что вам не нужно повторять эхо с вашего контроллера (что испортит модульные тесты, если они у вас есть).

1
ответ дан 6 December 2019 в 07:27
поделиться

Вы можете использовать те же действия для возврата XML, JSON или что-то еще, обнаруживая запросы ajax и, таким образом, имея возможность отличать запросы ajax от обычных. Например:

public function fooAction()
{
    if($this->getRequest->isXmlHttpRequest()) {
        echo json_encode($someData);
    } else {
        echo 'This is the normal output';
    }
}
8
ответ дан 6 December 2019 в 07:27
поделиться

Ваше представление может быть чем-то другим, кроме HTML, и либо конвейер может реагировать на запрос, являющийся сообщением ajax, либо ваш контроллер может реагировать. В любом случае это должно быть так просто, как вернуть другое представление.

2
ответ дан 6 December 2019 в 07:27
поделиться

Мой синтаксис может быть старше, но это набросок моего действия REST из моего контроллера индекса:

/**
 * 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;
}
0
ответ дан 6 December 2019 в 07:27
поделиться

Когда я использую ajax с codeigniter, я выводю прямо из контроллера.

Я также использую отдельный контроллер для простых запросов ajax, таких как отметка, избранное и т. Д. Для запросов ajax, таких как вход в систему, контакт и т. д. я бы добавил логику к обычному пути (например, domain.com/contact), обрабатывает запрос ajax. Затем я выводю json и завершаю выполнение сценария.

0
ответ дан 6 December 2019 в 07:27
поделиться
Другие вопросы по тегам:

Похожие вопросы: