php - Ajax POST Javascript 对象到 Zend Controller 并接收

标签 php javascript json zend-framework

我正在尝试将 javascript 对象从 View 传递到 Zend 中的更新 Controller 。

我的 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}]

并将其分配给变量 jsonObj

我的 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;
    }
    ;

我的更新 Controller 是:

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();

getPost() 方法只应在数据提交时使用带有 contentType application/x-www-form-urlencoded 的标识符。

还要确保您的 Javascript 变量 jsonObj 是包含 JSON 的字符串,而不是对象。如果它是一个对象,您将必须 jsonObj = JSON.stringify(jsonObj)

Docs for Zend Request Object


或者,您可以发送带有标识符的 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');

关于php - Ajax POST Javascript 对象到 Zend Controller 并接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17745333/

相关文章:

javascript - 使用socket io发送和获取数据的两条指令

javascript - D3 从 Python 函数获取数据

php - Highcharts 基本线

PHP Foreach if ... Zend 框架 ajax

php - 开发像 Stackoverflow 一样的聊天 API

javascript - 如何在一组 span 元素之后替换纯文本内容或文本节点?

python - 如何将 Python 对象(不可 JSON 序列化)从一个 (AWS) lambda 函数传递到另一个?

php - 如何将 HTML 代码从另一个文件添加到 .html 文件?

javascript - 我可以通过键入代码而不是单击 <a> 元素来访问 URL 吗?

javascript - 如何从父级调用原型(prototype)子方法