2017-04-16 183 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方法,它的工作原理非常好..謝謝大家