开发者

Using fancybox - how can I tell if an HTTP request is AJAX or not?

I'm using fancybox plugin to load a page and execute some code. The problem is that at times theres always the chance that someone would click on a link thats meant to be opened in a fancybox window before the page loads completely and the fancybox plugin is set up opening the page looking messed up in an complete browser window. Is there a way to tell whether an HTTP request is via ajax or not so I can set up my layouts accordingly.

I'm using the zend framework and have defined two layouts one for pages ope开发者_运维百科ned with fancybox and one is the regular page layout.


In you actions you can use isXmlHttpRequest() method to detect ajax request. For example, you could do:

public function onlyajaxAction() {

    if ($this->getRequest()->isXmlHttpRequest()) {
        // handel ajax request.           
    } else {
        // if not an ajax request, e.g. throw an exception or whatever
    }
}


You can check the X-Requested-With header, which is set to XMLHttpRequest by many Javascript libraries.


If you need to use a same action in different context to provide the according result, you may use the contextSwitcher() action helper (or ajaxContext())

<?php
class YourController extends Zend_Controller_Action
{
    public function init ()
    {
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        $ajaxContext->addActionContext('do-something', 'json')
            ->initContext();
    }

    public function doSomethingAction ()
    {
        // some logic here
        $this->view->data = $data;
    }
}

Use the ?format=json parameter to switch context, in case of JSON ZF will take care to convert $this->view->data to JSON for you, it will also disable layout, etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜