在Zend Framework中使用jQuery的getJSON

时间:2012-08-06 18:59:30

标签: jquery zend-framework getjson

我是jquery和zend的新手,尝试使用$ .getJSON在前端和后端之间进行通信。

所以这就是我所做的:

在/mycontroller/index.phtml的标头标签中,我有js代码:

 <script src="/js/jquery.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
    //  alert("js");
        $("#loadQuestions").submit(function(){
            var formData = $(this).serialize();
            console.log(formData);
            $.getJSON('http://xxx.com/mycontroller/process', formData, processData).error('ouch');
            function processData(data){
                //alert(data);
                console.log(data);
            }
            return false;
        }); // end submit
    }); // end ready
</script>
body标签中的

有一个简单的形式:

<form action="http://xxx.com/mycontroller/process" method="post" id="loadQuestions">
    <input type="hidden" name="page" value="100">
    <input type="submit" name="button" id="button" value="Submit" >
</form>
在processAction()中,有一些简单的代码:

$arr = array('pageNumber'=>200);
    echo json_encode($arr);
    exit;

我想要的是,在我点击提交后,应该收集表单数据(我可以在Chrome控制台中看到),但在我看到formData后,控制台中没有显示任何内容(我应该看到从服务器传递的数据,但我没有。)

有人知道我该怎么做才能修复它吗?

2 个答案:

答案 0 :(得分:0)

我认为你遇到了问题,因为你正试图从控制器打印。在Zend中,您必须在视图文件中执行此操作。

所以...在processAction中你应该做点像......

$this->view->data = $arr;

然后在视图文件process.phtml中你需要......

if($this->data)
    echo json_encode($this->data);

答案 1 :(得分:0)

您可以在控制器中使用AjaxContext操作助手。

我这样设置。

    public function preDispatch()
    {
        $this->_ajaxContentSwitch = $this->_helper->getHelper('AjaxContext');
        $this->_ajaxContentSwitch->addActionContext('process', 'json')
                                 ->initContext();
   }

并在你的流程行动中。

public function processAction()
{
    if ($this->_helper->ajaxContext()->getCurrentContext() == 'json') { 
                $this->view->array = array('pageNumber'=>200);
    } else {
        // Not called via ajax do redirect or something here
    }
}

你的JQuery脚本中的url也应该是“http://xxx.com/mycontroller/process/format/json”才能生效。

上面的processAction将返回一个名为array的json字符串,其中包含你的数组。

我希望这会有所帮助。

加里