Как я могу запросить параметры через ajax в Symfony? - PullRequest
0 голосов
/ 28 февраля 2020

Я хочу сделать запрос ajax, который отправляет переменную, в моем случае length другому

Это запрос ajax:

  var length = 5;

  $.ajax({
    method:'POST',
    data: {
      "id": id,
      "length": length,
      "start": start,
    },
    url:'{{ path('json', { 'fileName': output.fileName }) }}',
    success : function (data) {
       alert("success");
  } 

Контроллер:

  /**
  * @Route("/_json/{fileName}", name="json", methods={"GET","POST"})
  */
  public function jsonGenerator(JsonGenerator $jsonGenerator, $fileName) {
    $output = $jsonGenerator->getJson($fileName);
    return $output;
  }

Тогда мой класс:

class jsonGenerator {

  public function __construct(EntityManagerInterface $em, ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyAccessorInterface $propertyAccessor = null, PropertyTypeExtractorInterface $propertyTypeExtractor = null, ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null, callable $objectClassResolver = null, array $defaultContext = array()) {
    $this->em = $em;
  }



     public function getJson($fileName) {

        if(isset($request)){
          $length = $request->request->get('length');
        } else {
          $length = 10;
        }


        $file = 'files/'.$fileName.'.json';

        $input = file_get_contents($file);
        $array = json_decode($input);

        foreach ($array as $key => $value) {
          if($key == "data"){
            $new = array_slice($value, 0, length);
          }
        }

        $array->data = $new;

        $output = json_encode($array);

        return new Response($output);

       }
  }

Моя проблема в том, что мой запрос не выполняется. Длина остается всегда 10, но я ожидаю, что длина вывода будет равна 5.

Я что-то упустил?

1 Ответ

1 голос
/ 28 февраля 2020

в вашем классе и методе

public function getJson($fileName)

попробуйте сделать это

public function getJson($fileName, Request $request)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...