zend get with jQuery $.getJson
Does anyone know how to do this?
I want to point $.getJson() to a controller and have it return json through ajax based on request arguments. Unfortunately it appears Zend handles the get parameters different than jQuery encodes them.
How can I do this with Zend and j开发者_高级运维Query? I saw something on stackoverflow about Post arguments but I am lost when it comes to GET.
When using jQuery I get a 404 error using this code:
Client side:
$.getJSON("/entry/get-member-course",
{
"id": 1,
"format": "json"
},
function(json) {
alert("WIN");
});
Server side:
public function init() {
$this->_helper->ajaxContext->addActionContext('get-member-course', 'json')->initContext();
}
public function getMemberCourseAction() {
$this->view->test = Array("test"=>"bleh");
}
Easiest way is to use context switching. In your controller, setup the AjaxContext helper for your action with a "json" context
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');
}
}
The view for the calling script should contain a reference to the JSON URL. For example, say your JSON code is fired by clicking a link, create the link like this
<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>
Your client-side code would have something like this
$('#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
});
});
By default, when the JSON context is triggered, any view property is serialized as JSON and returned in the response. If your view properties cannot be simply converted, you need to disable automatic JSON serialization...
$this->_helper->ajaxContext->addActionContext('my-action', 'json')
->setAutoJsonSerialization(false)
->initContext();
and provide a JSON view script
// controllers/my/my-action.json.phtml
$simplifiedArray = array(
'prop' => $this->someViewProperty->getSomeValue()
);
echo Zend_Json::encode($simplifiedArray);
getJSON
encodes a JSON
string sequences such as {Person:{name: "Ken", age: "24"}}
, do you have corresponding decoder on your server side?
JSON PHP
Zend PHP JSON
精彩评论