javascript - 无法访问 symfony Controller 内的 javascript 变量

标签 javascript php jquery ajax symfony

在我的 symfony (v3.4) 项目中,我需要将一些 javascript 变量从我的 View 传递到包含表单的 Controller :我使用 Jquery 和 Ajax 将我的变量发送到正确的路径,但由于某种原因我无法访问它来 self 的 Controller 。

这是我的 Twig View 中的脚本部分:

$(".month").click(function() {

  var click = $(this);

  var month = click.val();
  var year = $("#years").val();

  var url = "{{ path('av_platform_saisie') }}";

  $.ajax(url, {
    type: 'POST',
    data: {
      'month': month,
      'year': year
    },
    success: function(data) {
      alert('OK');
    },
    error: function(jqXHR, textStatus, errorThrown) {}
  });

});

还有我的 Controller :

public function saisieAction(Request $request)
{

    $user = $this->getUser();
    $thisyear = date("Y");

    $em = $this->getDoctrine()->getManager();

    // Create the form
    $form = $this->get('form.factory')->createBuilder(FormType::class)
        ->add('ndf', CollectionType::class, array(
            'entry_type' => NoteDeFraisType::class,
            'label' => false,
            'allow_add' => true,
            'allow_delete' => true,
        ))
        ->getForm();


    // if the form has been submited
    if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {

        if($request->isXMLHttpRequest()){

            $month = $request->get('month');
            $year = $request->get('year');
            $sub_date = $month .'/' .$year;

        }

        $notesDeFrais = $form['ndf']->getData();


        foreach ($notesDeFrais as $ndf) {
            $ndf->setUser($user);
            $ndf->setMonth($sub_date);
            $em->persist($ndf);
        }

        $em->flush();


    }


    return $this->render('AvPlatformBundle:Platform:saisie.html.twig',
        array(
            'year' => $thisyear,  'form' => $form->createView()
        ));
}

奇怪的是:我尝试从一个新的 Twig View 发送我的 js 变量,该 View 不是由我的 Controller 渲染的,并且它使用完全相同的代码工作得很好,所以也许这是正常行为?

编辑: 我做了一些调试,实际上我的 if($request->isXMLHttpRequest()) 内的代码没有执行

最佳答案

您没有使用正确的语法来获取参数,这应该是这样的:

if($request->isXMLHttpRequest()) {
    $month=$request->request->get('month');
    $year=$request->request->get('year');
    $sub_date=$month .'/' .$year;
}

如果您想获取 GET 参数,就是这样:

$request->query->get('get_param');

关于javascript - 无法访问 symfony Controller 内的 javascript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56398579/

相关文章:

javascript - Mongodb嵌套文件更新?

javascript - Bootstrap 3.0 : added 2 sliders to home page both conflicting

php - 有没有办法在 php 中使用 Node js 库?

php - 匹配多行文本

javascript - Highcharts : plot line click event for multiple chart

javascript - 无法连接到 wss://(建立连接时出错:net::ERR_CONNECTION_CLOSED)

javascript - jqueryUI 可调整大小和可拖动不能一起工作

php - Symfony Controller 应该返回响应

javascript - CakePhp:JQuery/原型(prototype)

JQuery 自动完成在按回车键时提交数据