Php 将JSON对象发布到Symfony 2

Php 将JSON对象发布到Symfony 2,php,ajax,json,symfony,Php,Ajax,Json,Symfony,我正在使用symfony2进行一个项目,我已经构建了一个包来处理我所有的数据库服务,它来回传递JSON数据 我的问题: 可以发布一个直接的JSON对象吗?目前,我正在通过给对象一个名称json={“key”:“value”}来欺骗我的ajax调用的正常表单帖子,如果我不给它一个名称,我似乎无法从Symfony请求对象$json=$request->request->get('json')获取数据 我希望能够使用一个服务包来处理来自AJAX调用或普通Symfony表单的数据。目前,我正在使用提交

我正在使用symfony2进行一个项目,我已经构建了一个包来处理我所有的数据库服务,它来回传递JSON数据

我的问题:

  • 可以发布一个直接的JSON对象吗?目前,我正在通过给对象一个名称
    json={“key”:“value”}
    来欺骗我的ajax调用的正常表单帖子,如果我不给它一个名称,我似乎无法从Symfony请求对象
    $json=$request->request->get('json')获取数据

  • 我希望能够使用一个服务包来处理来自AJAX调用或普通Symfony表单的数据。目前,我正在使用提交的Symfony表单,获取数据,然后使用JSON_ENCODE,我只是不知道如何将数据发布到我的服务控制器,该控制器需要请求数据

总结如下:

  • 我希望Symfony接受JSON post对象,而不是表单

  • 我想使用请求/响应在控制器之间传递JSON对象

如果我在这件事上完全错了,尽管告诉我吧

页面上的javascript:

function submitPostForm(url, data) {
    var form                = document.createElement("form");
        form.action         = url;
        form.method         = 'POST';
        form.style.display  = 'none';

    //if (typeof data === 'object') {}

    for (var attr in data) {
        var param       = document.createElement("input");
            param.name  = attr;
            param.value = data[attr];
            param.type  = 'hidden';
        form.appendChild(param);
    }

    document.body.appendChild(form);
    form.submit();
}
在某些事件之后(如单击“提交”):

在控制器中:

   /**
    * @Route("/varelager/bestilling", name="_varelager_bestilling")
    * @Template()
    */
   public function bestillingAction(Request $request) {
       $products   = $request->request->get('products', null); // json-string
       $action     = $request->request->get('action', null);

       return $this->render(
           'VarelagerBundle:Varelager:bestilling.html.twig',
           array(
               'postAction' => $action,
               'products' => $products
           )
       );
   }
在模板中(在我的例子中为bestilling.html.twig):


如果要在控制器中检索在请求正文中作为标准JSON发送的数据,可以执行以下类似操作:

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_decode()
调用中的
true
参数值,以获取
stdClass
对象。

我编写了方法,以获取数组形式的内容

protected function getContentAsArray(Request $request){
    $content = $request->getContent();

    if(empty($content)){
        throw new BadRequestHttpException("Content is empty");
    }

    if(!Validator::isValidJsonString($content)){
        throw new BadRequestHttpException("Content is not a valid json");
    }

    return new ArrayCollection(json_decode($content, true));
}
我使用如下所示的方法

$content = $this->getContentAsArray($request);
$category = new Category();
$category->setTitle($content->get('title'));
$category->setMetaTitle($content->get('meta_title'));

感谢您的快速回复!实际上,您仍然在使用javascript提交一个普通表单,这就是我目前正在做的事情,我想知道是否可以直接发布JSON对象而不模拟表单,如果不是戏剧的话。另外,一旦我在Symfony中有了JSON对象,是否可以将其作为请求对象发送到另一个服务?我在编辑中提到了您的评论。我不太确定在没有jQuery的情况下如何使用ajax,所以我将把这个问题留给您。要将某人发送到另一个控制器,您可以将其重定向到那里。这将在重定向和转发下介绍。祝你好运再次感谢您,我应该更清楚一点,我可以提交对象没有问题,我只是无法在控制器中检索它,如果没有名称$request->request->get('action',null)等于$request->request->get('action'),当然如果您在ajax请求中使用JSON.stringify({'key1':'value1'))。控制器将接收它作为json对象,另一个案例发送:“key1=value1&key2=value2”,查询字符串。并且必须使用$request->get('key1')。我觉得第一个比较干净。谢谢你的回复。事实上,我是这样在周末工作的:$JSON=file\u get\u contents(“php://input"); 这样做有什么问题吗?
php://input
为一次性只读。一旦您阅读了内容,除非您将数据传递给其他人,否则无法再次阅读。使用Symfony2请求对象可确保在需要时,您可以在请求过程中再次获取数据,而无需传递例如
$JSON
变量。该函数需要请求参数:public function yourAction(request$request)@whistergreg无问题!:-)通过参数传入请求对象是可选的;您应该能够根据上面的代码删除它并从容器中获取它,或者传入它。有关不同的变体,请参见和。此变体存在一个问题:无法将此类请求绑定到表单。有没有办法做到这一点?symfony上默认存在validator类?数组没有方法,bro.ArrayCollection是一个类。
public function yourAction()
{
    $params = array();
    $content = $this->get("request")->getContent();
    if (!empty($content))
    {
        $params = json_decode($content, true); // 2nd param to get as array
    }
}
protected function getContentAsArray(Request $request){
    $content = $request->getContent();

    if(empty($content)){
        throw new BadRequestHttpException("Content is empty");
    }

    if(!Validator::isValidJsonString($content)){
        throw new BadRequestHttpException("Content is not a valid json");
    }

    return new ArrayCollection(json_decode($content, true));
}
$content = $this->getContentAsArray($request);
$category = new Category();
$category->setTitle($content->get('title'));
$category->setMetaTitle($content->get('meta_title'));