如何通过ajax显示带有twig的变量?

问题描述 投票:0回答:1

我有一个函数,通过Ajax在我的页面上加载一个表单。

mypage.html.twig:

function forms(e,el) {

  var id = $(el).attr("data-id");
  var target = $(el).attr("data-target");

  e.preventDefault();
  var $link = $(e.currentTarget);
  $.ajax({
      method:'POST',
      data: {
        "id": id,
        "target": target
      },
      url: $link.attr('href')
  })
}


$('.create-item').on( 'click', function (e) {
      forms(e,this);
});

MyController.php

  $response = new JsonResponse(
        array(
          'message' => 'Success',
          'output' => $this->renderView('form.html.twig',
          array(
            'entity' => $item,
            'form' => $form->createView(),
          ))), 200);
          return $response;

这是加载的表单(form.html.twig):

<section class="content-header" style="margin-bottom:20px">
  <h1 style="float:left;margin-bottom:30px">{{ target }}</h1>
</section>
<section class="content" style="clear:left">
  <div class="form-group">
    {{ form_start(form) }}
    {{ form_end(form) }}
  </section>

表单已正确加载。但在<h1></h1>地区,我想加载变量target

它无法正常工作,我收到一条错误消息:

变量“目标”不存在。

php json ajax symfony twig
1个回答
2
投票

您没有将发布的值target传递给您的视图

$response = new JsonResponse(
        array(
          'message' => 'Success',
          'output' => $this->renderView('form.html.twig',
          array(
            'entity' => $item,
            'form' => $form->createView(),
            'target' => $target, //<-----
          ))), 200);
          return $response;
© www.soinside.com 2019 - 2024. All rights reserved.