Php 如何在Symfony中通过ajax请求参数?

Php 如何在Symfony中通过ajax请求参数?,php,json,ajax,symfony,Php,Json,Ajax,Symfony,我想发出一个ajax请求,向另一个发送一个变量,在我的例子中是length 这是ajax请求: var length = 5; $.ajax({ method:'POST', data: { "id": id, "length": length, "start": start, }, url:'{{ path('json', { 'fileName': out

我想发出一个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 = []
    ){
        $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 ('data' == $key) {
                $new = \array_slice($value, 0, length);
            }
        }

        $array->data = $new;

        $output = json_encode($array);

        return new Response($output);
    }
}
我的问题是,我的请求没有通过。 长度始终保持为10,但我希望输出的长度为5


我遗漏了什么吗?

在你的课程和方法中

公共函数getJson($fileName)

试着这样做


公共函数getJson($fileName,Request$Request)

实际上需要将请求注入函数中。您的长度始终为10,因为
if(isset($request)){
始终未设置。您的函数应该更像
公共函数jsonGenerator($fileName,request$request,jsonGenerator$jsonGenerator){
和ofc您需要将
$request
传递给下面的被调用函数。@Andrei我按照您的建议将其更改为
公共函数jsonGenerator(jsonGenerator$jsonGenerator,request$request,$fileName){
但长度仍然是10。您是否也将请求向下传递到
$jsonGenerator->getJson($fileName);
?您的意思是:
$jsonGenerator->getJson($fileName,length)
?不。不,我不是这个意思。也许你应该复习一下PHP中函数之类的基础知识。这似乎更像是对编码的基本理解,而不是一个实际问题。你在X范围内有一个变量,你希望它在函数Z的Y范围内。你必须通过它的参数将变量X传递给函数Z。答案是
public functtion jsonGenerator(jsonGenerator$jsonGenerator,请求$Request,$fileName){$length=$Request->Request->get('length');$output=$jsonGenerator->getJson($fileName,$length);