【问题标题】:How can I request parameters via ajax in Symfony?如何在 Symfony 中通过 ajax 请求参数?
【发布时间】:2020-06-12 14:44:46
【问题描述】:

我想发出一个 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。

我错过了什么吗?

【问题讨论】:

  • 您确实需要将请求注入到函数中。您的长度始终为 10,因为始终未设置 if(isset($request)){。您的函数应该看起来更像这样 public function jsonGenerator($fileName, Request $request, JsonGenerator $jsonGenerator) { 并且您需要将 $request 传递给被调用的函数。
  • @Andrei 我按照您的建议将其更改为public function jsonGenerator(JsonGenerator $jsonGenerator, Request $request, $fileName) {,但长度仍为 10。
  • 您是否也将请求传递给$jsonGenerator->getJson($fileName);
  • 你的意思是这样的:$jsonGenerator->getJson($fileName,length);?
  • 没有。不,我不是那个意思。也许您应该复习 PHP 中的函数等基础知识。这似乎更像是对编码的基本理解,而不是实际问题。您在 X 范围内有一个变量,并且您希望它在函数 Z 的 Y 范围内。您必须通过变量 X 的参数将变量 X 传递给函数 Z。

标签: php json ajax symfony


【解决方案1】:

在你的方法

public function getJson($fileName)

尝试这样做

public function getJson($fileName, Request $request)

【讨论】:

  • 答案是public function jsonGenerator(JsonGenerator $jsonGenerator, Request $request, $fileName) { $length = $request->request->get('length'); $output = $jsonGenerator->getJson($fileName,$length);
猜你喜欢
  • 2015-07-22
  • 2016-12-20
  • 2012-04-04
  • 1970-01-01
  • 2017-09-23
  • 2018-11-10
  • 2019-03-06
  • 2020-09-05
  • 1970-01-01
相关资源
最近更新 更多