dtjzpg5313 2009-07-07 11:11
浏览 43
已采纳

Zend Framework - 在控制器中传递变量以进行ajax调用

Hi out there in Stackland! Here's my problem:

I want to use my Zend controller to load an array from a database, and then pass it to javascript. I've decided the best way to do this is to use ajax to ask the controller for it's array, encode it in json, and then pass it down. However, I don't know how to pass the variable I loaded in my first action to the action that will pass it down when it gets called via ajax.

The original action which produces the view

public function indexAction()
    {
            $storeid = $this->getStoreId();

            if(!$storeid)
            {
                 $this->_forward('notfound');
                 return;
            }

            $store = $this->_helper->loadModel('stores');
            $store->getByPrimary($storeid);
    }

The action that will be called via ajax

public function getdataAction()
        {
            $this->_helper->Layout->disableLayout(); // Will not load the layout
            $this->_helper->viewRenderer->setNoRender(); //Will not render view

            $jsonResponse = json_encode($store);
            $this->getResponse()->setHeader('Content-Type', 'application/json')
                                ->setBody($jsonResponse);

        }

What I want is to pass $store in indexAction to getdataAction so it can send store as the jsonResponse. Note, these are called at two different times.

Things I have tried that haven't worked:

  1. setting $this->getRequest()->setParam('store', $store) in indexAction, and then using $this->getRequest()->getParam('store'), in getdataAction. I presume this hasn't worked because they're different http requests, so attaching a new param is useless.

  2. using protected $_store in the controller itself, and then saving to it with indexAction, and using it in getdataAction. I'm not really sure why this isn't working.

Is there a good way to pass a variable in this manner? Is there a way to pass a variable between different controllers?(I assume the answer to one is the answer to the other). Could I store it in a controller helper? Do I have to use a session, which I know would work but seems unnecessary? Is there a better way to pass variables to javascript? Am I asking too many questions? Any help would be outstanding. Thanks.

展开全部

  • 写回答

5条回答 默认 最新

  • doujing6053 2009-07-07 15:02
    关注

    Maybe I'm reading the question wrong, but you should be able to just move $store into the constructor:

    public function __construct() {
        $store = $this->_helper->loadModel('stores');
        $store->getByPrimary($storeid);
    }
    

    and have it accessible in all *Action methods. Using sessions seems out of whack for this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部