MVC: how to ajax?

前端 未结 6 805
我在风中等你
我在风中等你 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:23

    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.

提交回复
热议问题