发布JSON对象Symfony的2 [英] Posting JSON objects to Symfony 2

查看:133
本文介绍了发布JSON对象Symfony的2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用的Symfony 2的一个项目,我已经建立了一个包来处理它通过JSON数据向后和向前的我所有的数据库服务。

I'm working on a project using Symfony 2, I've built a bundle to handle all my database services which passes JSON data back and forward.

我的问题/问题:

  • 有没有可能发布直线上升JSON对象?目前,我通过给对象的名称欺骗一个正常的表单提交我的Ajax调用 JSON = {关键:值} ,如果我不给它一个名字,我似乎无法得到从Symfony的请求对象中的数据 $ JSON = $请求 - >请求 - >获得(JSON);

  • Is it possible to post a straight up JSON object? Currently I'm spoofing a normal form post for my ajax calls by giving the object a name json={"key":"value"} if I don't give it a name I can't seem to get the data from the Symfony request object $JSON = $request->request->get('json');

我希望能够用一个服务包来同时处理数据即将从AJAX调用,还是正常Symfony的形式。目前,我正在提交Symfony的形式,获取数据,然后使用JSON_EN code,我只是不知道如何通过我的服务控制器,它期望请求数据发布的数据。

I want to be able to use the one service bundle to handle both data coming from AJAX calls, or a normal Symfony form. Currently I'm taking the submitted Symfony form, getting the data then using JSON_ENCODE, I just can't work out how to post the data through to my services controller which is expecting request data.

要总结: - 我想的Symfony接受JSON对象后,而不是一种形式。 - 我想通过使用请求控制器之间的JSON对象/响应

To Summarize: - I want Symfony to accept a JSON post object rather than a form. - I want to pass the JSON object between controllers using Request/Response

如果我要对此都错了,请随时告诉我呢!

If I'm going about this all wrong, feel free to tell me so!

推荐答案

如果您希望检索一直被作为标准的JSON的请求体在控制器的数据,你可以做类似下面的内容:

If you want to retrieve data in your controller that's been sent as standard JSON in the request body, you can do something similar to the following:

public function yourAction()
{
    $params = array();
    $content = $this->get("request")->getContent();
    if (!empty($content))
    {
        $params = json_decode($content, true); // 2nd param to get as array
    }
}

现在 $ PARAMS 将是一个数组全是你的JSON数据。除去在 json_de code中的参数值()打电话以获得 stdClass的对象。

Now $params will be an array full of your JSON data. Remove the true parameter value in the json_decode() call to get a stdClass object.

这篇关于发布JSON对象Symfony的2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆