AngularJS POST JSON数据到Symfony2

时间:2014-03-24 13:36:01

标签: ajax angularjs symfony http-post

我想知道为什么这不起作用,我有一个AngularJS应用程序通过AJAX数据发送到Symfony2应用程序。如您所见,数据在我的网络控制台中发送

<?php

namespace Supbox\CloudBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
class FolderController extends Controller
{
    public function createAction(){
        $post = $this->getRequest()->request;
        $name = $post->get("name");
        $folder = $post->get("folder");
        var_dump($post);
        die; 
    }
}

AngularJS代码

    $http({
            method: 'POST', 
            url: route.folder.create, 
            data: {
                folder: $scope.id,
                name: name
            }
        })

Opera网络控制台输出

Request URL:http://localhost/supbox/web/box/folder/create
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept-Encoding:gzip,deflate,lzma,sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:25
Content-Type:application/json;charset=UTF-8
Host:localhost
Origin:http://localhost
Referer:http://localhost/supbox/web/box/
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36 OPR/20.0.1387.82
Request Payloadview source
{folder:1, name:Ang}
Response Headersview source
Connection:Keep-Alive
Content-Length:431
Content-Type:text/html
Date:Mon, 24 Mar 2014 13:25:53 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.4 (Win64) OpenSSL/1.0.1d PHP/5.4.12
X-Powered-By:PHP/5.4.12

3 个答案:

答案 0 :(得分:4)

如果您(Angular JS)通过标头将数据发布为JSON,则需要更改您的代码:

public function createAction(){
    $post = $this->getRequest()->getContent();
    $post = json_decode($post);
    $name = $post->name;
    $folder = $post->folder;
    var_dump($post);
    var_dump($name); // null
    var_dump($folder); // null
    die; 
}

答案 1 :(得分:0)

不知道为什么,Angular $ http将数据作为请求体发送,JSON编码,而Symfony2正在读取$ _GET和$ _POST数组。

所以你有2个解决方案:

1-更新Php代码,您可以覆盖SF2请求类(https://gist.github.com/ebuildy/fe1e708e466dc13dd736

2-更新Js代码,您可以“转换”$ http请求(https://gist.github.com/bennadel/11212050

答案 2 :(得分:0)

已经创建了一个捆绑来解决这个问题,而且非常轻。

qandidate-labs/symfony-json-request-transformer