zend得到jQuery $ .getJson

时间:2011-08-15 22:55:34

标签: zend-framework

有谁知道怎么做?

我想将$ .getJson()指向一个控制器并让它根据请求参数通过ajax返回json。不幸的是,看起来Zend处理的get参数与jQuery编码不同。

如何使用Zend和jQuery执行此操作?我在stackoverflow上看到了关于Post参数的内容,但是当涉及GET时我迷失了。

使用jQuery时,我使用以下代码收到404错误:


客户方:

$.getJSON("/entry/get-member-course",
{
    "id": 1,
    "format": "json"
},
function(json) {
    alert("WIN");
});

服务器端:

public function init() {
    $this->_helper->ajaxContext->addActionContext('get-member-course', 'json')->initContext();
}

public function getMemberCourseAction() {
    $this->view->test = Array("test"=>"bleh");        
}

2 个答案:

答案 0 :(得分:1)

最简单的方法是使用上下文切换。在您的控制器中,使用“json”上下文为您的操作设置AjaxContext帮助程序

class EntryController extends Zend_Controller_Action
{
    public function init()
    {
        $this->_helper->ajaxContext->addActionContext('get-member-course', 'json')
                                   ->initContext();
    }

    public function getMemberCourseAction()
    {
        $id = $this->_getParam('id');

        $this->view->test = array('test' => 'bleh');
    }
}

调用脚本的视图应包含对JSON URL的引用。例如,假设您的JSON代码通过单击链接触发,请创建此链接

<a id="get-json" href="<?php echo $this->url(array(
    'action'     => 'get-member-course',
    'controller' => 'entry',
    'id'         => $someId
), null, true) ?>">Click me for JSON goodness</a>

您的客户端代码会有类似的内容

$('#get-json').click(function() {
    var url = this.href;
    $.getJSON(url, {
        "format": "json" // this is required to trigger the JSON context
    }, function(data, textStatus, jqXHR) {
        // handle response here
    });
});

默认情况下,触发JSON上下文时,任何视图属性都将序列化为JSON并在响应中返回。如果无法简单地转换视图属性,则需要禁用自动JSON序列化...

$this->_helper->ajaxContext->addActionContext('my-action', 'json')
                           ->setAutoJsonSerialization(false)
                           ->initContext();

并提供JSON视图脚本

// controllers/my/my-action.json.phtml
$simplifiedArray = array(
    'prop' => $this->someViewProperty->getSomeValue()
);
echo Zend_Json::encode($simplifiedArray);

答案 1 :(得分:0)

getJSONJSON字符串序列进行编码,例如{Person:{name: "Ken", age: "24"}},您的服务器端是否有相应的解码器?

JSON PHP

Zend PHP JSON

相关问题