2017-04-16 150 views
1

我想从树枝视图到symfony的控制器发送数据使用角JS $ HTTP方法 这是我的javascript

<script> 
var app = angular.module('app',[]); 
app.controller('ctrl',function($scope,$http) { 


$scope.processForm = function() { 
    var val = $scope.libelle; 
    $http({ 
     method: "POST", 
     url: 'http://localhost/symangular/web/app_dev.php/home', 
     headers: { 
      'Content-Type': 'application/json' 
     }, 
     data:{libelle:val} 
    }).then(function (html) { 
    console.log(html); 


    }); 
} 

}); 
</script> 

,这是我的控制器

class DefaultController extends Controller 
{ 
public function indexAction(Request $request) 
{ 
    $prod = new Product(); 
    $form = $this->createForm(ProductType::class,$prod); 
    $form->handleRequest($request); 
    if($form->isSubmitted() && $form->isValid() && $request- >isMethod('POST') && $request->isXmlHttpRequest()){ 
     $em = $this->getDoctrine()->getManager(); 
     $data = json_decode($request->getContent(), true); 
     dump($request->request->get('libelle')); 
     $request->request->replace($data); 
     $prod->setLibelle($request->request->get('libelle')); 
     $em->persist($prod); 
     $em->flush(); 
     return new JsonResponse("good"); 
    } 
    return $this->render('angulartestangularBundle:Default:index.html.twig',array('form'=>$form->createView())); 
} 

} 

所以当我执行我得到了在控制台中的对象,我不明白这也我没有什么数据库,有没有人有关于如何处理的symfony控制器的 $ HTTP请求角的想法

Object {data: "<script src="https://ajax.googleapis.com/ajax/libs…: 5 }  ); })();/*]]>*/</script>↵</body>↵", status: 200, config: Object, statusText: "OK"} 
+1

你的'dump()'可能会扰乱你的Json,使其无效。尝试删除它。 – Growiel

回答

2

在Symfony中,请求通过读取请求标头而被视为XmlHttpRequest。在Symfony的完全相同的代码是:

public function isXmlHttpRequest() 
{ 
    return 'XMLHttpRequest' == $this->headers->get('X-Requested-With'); 
} 

因此,使用angularjs或任何JavaScript框架,使一个XMLHttpRequest时,你应该添加一个标头X-Requested-With key和value = XMLHttpRequest。即使您使用的是fetch API,也需要此标头。在你的代码abow,请求调用应该是:

$http({ 
    method: "POST", 
    url: 'http://localhost/symangular/web/app_dev.php/home', 
    headers: { 
     'Content-Type': 'application/json', 
     'X-Requested-With': 'XMLHttpRequest' 
    }, 
    data:{libelle:val} 
}) 

如果你不希望添加这个头每次通话$http功能,您可以将其作为默认的配置添加到$httpProvider

angular 
    .module('yourModuleName', []) 
    .config(['$httpProvider', function ($httpProvider) { 
     $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; 
    }]) 
; 

有关$http配置以及如何设置默认配置的详细信息,请参阅Angularjs Documentation

0

您的方法有点困惑,因此很难调试。

其良好实践(IMO)将您的API端点与呈现页面的控制器操作分开。将它们耦合在一起会严重限制应用程序的可扩展性。

它有可能失败了控制器操作中复杂if语句的一部分;这使得很难调试。

它也是一个很好的做法,当写一个API来向客户提供一个想法在通话中出了什么问题。 (即使它只有你访问API)

看着你的代码,它也看起来像你在处理请求混淆。您的验证提交是基于Product,并要求symfony在此基础上处理数据,但随后在提交的if语句中,再次提取数据。

您仍然可以利用symfony表单通过解耦并通过这种方式进行验证。

/** 
* If your using annotated routing do this, or make the equivelent in your yaml file. 
* @Route("/api/product/create", name="api_product_create") 
*/ 
public function productAction(Request $request) 
{ 
    $data = json_decode($request->getContent(), true); 

    if(!$data) 
    { 
     // youll want to handle this exception with a listener or somesuch so that it sends back a nice neat message to your client 
     throw new InvalidArgumentException('Invalid json'); 
    } 

    $product = new Product(); 
    // create your form as you did before. 
    $form = $this->createForm(ProductType::class,$product); 

    // this tells symfony to fill out the form, as if it was submitted conventionally. 
    $form->submit($data); 

    // now we can check for valid (you dont need to check submitted, as valid will do that anyway) 
    if($form->isValid()) 
    { 
      // persist the new object 
      $em = $this->getDoctrine()->getManager(); 
      $em->persist($prod); 
      $em->flush(); 

      // create a new set of return data 
      $return = [ 
       'status' => 'success', 
       'productId' => $product->getId(), 
      ]; 

      return new JsonResponse($return, 201); 
    } 


     // oops, something went wrong, find out and report it 
    $return = [ 
     'status' => 'error', 
     'uri' => $request->getPathInfo(), 
     'errors' => (string) $form->getErrors(true, false), 
    ]; 

    return new JsonResponse($return, 400); 
} 

然后,在您的模板中,将URL正确呈现到端点。

url: {{ path('api_product_create') }}, 

这只是一个例子,可能无法完全满足您的用例,但你可以看到,一旦脱钩其更容易找到出了什么问题以及哪里。

有用的资源:

0

谢谢大家ansewring我的问题..的信息是如此helpfull ..否则解决方案是分离symfony控制器中的两个动作,并添加请求标头$ http方法,它的工作原理非常好..谢谢大家