我正试图将javascript对象从视图传递到Zend中的更新控制器。
我的JSON字符串看起来像:
[{"item_id":null,"parent_id":"none","depth":0,"left":"1","right":4},{"item_id":"1","parent_id":null,"depth":1,"left":2,"right":3}]
并将其分配给变量CCD_ 1。
我的AJAX帖子看起来像:
$.ajax({
type: "POST",
url: "http://dev.jp-websolutions.co.uk/cms_nishan/admin/navigation/update",
data: jsonObj,
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data, null, 4));
},
error: function() {
alert("failure");
}
});
return false;
}
;
我的更新控制器是:
public function updateAction() {
if ($this->getRequest()->isXmlHttpRequest()) {
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
}
$data = $this->_request->getPost();
$result = Zend_Json::decode($data);
print_r($result);
}
但如果我使用,我就无法让它工作
$result = Zend_Json::decode([{"item_id":null,"parent_id":"none","depth":0,"left":"1","right":4},{"item_id":"1","parent_id":null,"depth":1,"left":2,"right":3}]);
它正确显示为
Array (
[0] => Array (
[item_id] =>
[parent_id] => none
[depth] => 0
[left] => 1
[right] => 4 )
[1] => Array ( [item_id] => 1 [parent_id] => [depth] => 1 [left] => 2 [right] => 3 ) )
我怎样才能得到这份工作?任何帮助都将不胜感激:)
您发送的JSON作为请求主体,没有标识符,因此在PHP方面,您需要使用getRawBody()
来获得JSON:
$data = $this->getRequest()->getRawBody();
只有在提交数据时使用contentType为application/x-www-form-urlencoded
的标识符时,才应使用getPost()
方法。
还要确保您的Javascript变量jsonObj
是包含JSON的字符串,而不是对象。如果是一个对象,则必须使用jsonObj = JSON.stringify(jsonObj)
。
Zend请求对象的文档
或者,您可以发送带有标识符的JSON。将ajax更改为:
$.ajax({
type: "POST",
url: "http://dev.jp-websolutions.co.uk/cms_nishan/admin/navigation/update",
data: {json : jsonObj},
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data, null, 4));
},
error: function() {
alert("failure");
}
});
return false;
};
在PHP方面,使用getPost('json')
:
$data = $this->_request->getPost('json');
在ajax、中为Data属性使用对象
$.ajax({
type: "POST",
url: "http://dev.jp-websolutions.co.uk/cms_nishan/admin/navigation/update",
data: {myData: jsonObj,somethingLese: 'else'},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data, null, 4));
},
error: function() {
alert("failure");
}
});
return false;
}
;
在控制器中,使用$this->getRequest()->getParam('myData', null);
访问数据。
public function updateAction() {
if ($this->getRequest()->isXmlHttpRequest()) {
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
}
$data = $this->getRequest()->getParam('myData', null);
$result = Zend_Json::decode($data);
print_r($result);
}
Zend请求