donoworuq450547191
2018-08-13 16:56
浏览 74
已采纳

如何在symfony路由中传递数组?

I have a function in my controller that takes an array as input. The value is passed from ajax. At the moment it is not being decoded correctly.

 /**
 * @Route("/userLogin/{params}", name="userLogin", methods={"POST"})
 * @param UserdbRepository $repository
 * @param $params
 * @return \Symfony\Component\HttpFoundation\Response
 */

public function userLogin(UserdbRepository $repository, $params) {

   $email = $params[0];
   $pass = $params[1];

   print_r($params);  // output correct value test@test.com
   echo $params[0];   // output t
   echo $email;       // output t

   .... rest of code
}

js:

 const array = [ 'email', 'pass' ]

 $.ajax({
    url: `/userLogin/${array}`,
    type: "post",
    dataType: 'json'
})

图片转代码服务由CSDN问答提供 功能建议

我的控制器中有一个函数,它将数组作为输入。 该值从ajax传递。 目前它没有被正确解码。

  / ** 
 * @Route(“/ userLogin / {params}”,name =“userLogin”,methods =  {“POST”})
 * @param UserdbRepository $ repository 
 * @param $ params 
 * @return \ Symfony \ Component \ HttpFoundation \ Response 
 * / 
 
公共函数userLogin(UserdbRepository $ repository,$  params){
 
 $ email = $ params [0]; 
 $ pass = $ params [1]; 
 
 print_r($ params);  //输出正确的值test@test.com 
 echo $ params [0];  //输出t 
 echo $ email;  //输出t 
 
 ......其余代码
} 
   
 
 

js:

  const array = ['email','pass'] 
 
 $ .ajax({
 url:`/ userLogin / $ {array}`,
 type:“post”,
 dataType:'json  '
})
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpcnm2132 2018-08-13 17:05
    已采纳

    Use Request component Symfony\Component\HttpFoundation\Request you can autowire it: public function userLogin(UserdbRepository $repository, Request $request)

    Example 1: fetch params from requestBody:

    $email = $request->request->get('email', null); $email will be null if 'email' parameter not provided in request

    don't forget to pass data property in your ajax request

    const requestBody = {
        'email': 'asd@example.com',
        'pass': '123',
    };
    
    $.ajax({
        url: `/userLogin/`,
        type: "post",
        data: requestBody,
    });
    

    Note: don't send data in json format. Also you can remove {params} from your @Route pattern and $params argument.

    Example 2: fetch 'email' param from queryString:

    $email = $request->query->get('email', null);

    https://symfony.com/doc/current/components/http_foundation.html

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题