使用Rest POST将数据从Angularjs form发送到symfony2


send data from angularjs form to symfony2 with Rest POST

我正在 http://welcometothebundle.com/web-api-rest-with-symfony2-the-best-way-the-post-method/遵循本教程,但我有一个angularjs客户端和一个带有symfony的rest API。

我的问题是我仍然不知道如何将数据从angularjs中的表单发送到symfony2的控制器,然后发送到数据库Mysql。

更新:我知道如何在客户端控制器中静态添加数据到数据库,但是如何使用 angularjs 形式的值来做到这一点

public function insertAction()
    {
$client = new Client();
    $client->setName('cccccccc');
    $client->setAdress('ffffffff');
    $client->setCivilit('sssssssss');
    $em = $this->getDoctrine()->getManager();
    $em->persist($client);
    $em->flush();
    return new Response('Id du client créé : '.$client->getId());

这是应用程序.js我在其中定义了控制器:

.controller('PostsCtrlAjax1', ['$scope', '$http' ,function($scope,$http) {
   $http({method: 'POST', url: 'http://localhost/operation/web/app_dev.php/apiclient/insertcl.json'})
   .success(function(data){
        $scope.posts = data; // response data 
   }).error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
    console.log("data error ...");
  });
}]);

当我运行我的客户端 angularjs 时,静态数据将被存储在数据库中任何想法请并感谢您的帮助。

你可以使用这个:

$info = $request->getContent();
$data = json_decode($info,true);

然后使用: $client->setName($data['name']);

因此,要将数据从angularJS客户端存储到symfony2服务器,您必须执行以下操作:

安装一个简单的侦听器来处理 Symfony 中的 json 请求

Qandidate-labs/symfony-json-request-transformer

客户端窗体(示例)

<form ng-submit="submitForm()">
    <input ng-model="postData.name"/>
    <input ng-model="postData.address"/>
    <input ng-model="postData.civility"/>
</form>

提交表单操作(客户端)

$scope.postData = {};
$scope.submitForm = function(){
    $http.post('http://localhost/operation/web/app_dev.php/apiclient/postRoute', $scope.postData);
        .success(function(data){
            $scope.posts = data; // response data, not get data from DB.
        }).error(function(data, status, headers, config) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
            console.log("data error ...");
        });
};

存储操作(服务器)

use Symfony'Component'HttpFoundation'JsonResponse;
use Symfony'Component'HttpFoundation'Request;
//...
public function insertAction()
{
    $request = new Request();
    $request = $request->createFromGlobals();
    $client = new Client();
    $client->setName($request->request->get('name'));
    $client->setAdress($request->request->get('address'));
    $client->setCivilit($request->request->get('civility'));
    $em = $this->getDoctrine()->getManager();
    $em->persist($client);
    $em->flush();
    return new JsonResponse('Id du client créé : '.$client->getId());
}

如果要返回重新加载范围变量的数据,请将其添加到您的方法中:

//...
$clients = $em->getRepository('YourBundle:Client')->findAll();
//...

并将您的返回更改为 :

//...
return new JsonResponse($clients);

然后,返回的响应将包含您的数据,并且 $scope.posts 将使用新的注册数据刷新。