Javascript 控制器API向Ajax返回状态为200但为空数组的响应

Javascript 控制器API向Ajax返回状态为200但为空数组的响应,javascript,ajax,symfony,Javascript,Ajax,Symfony,我完全被Ajax请求卡住了。我试图向Ajax发送一个响应,并将一个编码数组发送到json。Ajax得到status200响应,但只发送字符串;不是我的变量。 我想知道问题是否是由于异步。。。当我使用Postman进行测试时,我可以看到完整的响应,但是Js给了我:{“recipies”:[]} 谢谢你的帮助 阿贾克斯: searchByIngredients: function () { console.log('Search for recipies'); va

我完全被Ajax请求卡住了。我试图向Ajax发送一个响应,并将一个编码数组发送到json。Ajax得到status200响应,但只发送字符串;不是我的变量。 我想知道问题是否是由于异步。。。当我使用Postman进行测试时,我可以看到完整的响应,但是Js给了我:{“recipies”:[]}

谢谢你的帮助

阿贾克斯:

searchByIngredients: function () {
        console.log('Search for recipies');

        var array = [];
        var ingredients = $('.span-ingredient');
        ingredients.each(function () {
            array.push(this.innerHTML);
        });
        console.log(array);
        console.log(Array.isArray(array));
        $.ajax(
            {
                url: Routing.generate('shopping_list_by_ingredients_ajax'),
                type: "POST",
                contentType: "application/json",
                dataType: "json",
                data: JSON.stringify(array)
            }).done(function (response) {
                if (null !== response) {
                    console.log('ok : ' + JSON.stringify(response));
                    console.log(typeof(response));
                } else {
                    console.log('Error');
                }
            }).fail(function (jqXHR, textStatus, error) {
                console.log(jqXHR);
                console.log(textStatus);
                console.log(error);
            });
    }
};
控制器:

/**
 * @Route("/by-ingredient-ajax", name="shopping_list_by_ingredients_ajax", options={"expose"=true}, methods={"GET","POST"})
 *
 * @return JsonResponse|Response
 */
public function createShopplistByIngredientsAjax(Request $request, RecipeIngredientRepository $recipeIngredientRepository, RecipeRepository $recipeRepository)
{
    if ($request->isMethod('POST')) {
        $dataIngredients = json_decode($request->getContent());
        $dataIngredients = $request->getContent();

        // Sorry for this :/
        $arrayIngredients = explode(', ', $dataIngredients);
        $text = str_replace("'", '', $arrayIngredients);
        $text2 = str_replace('[', '', $text);
        $text3 = str_replace(']', '', $text2);
        $recipiesArray = [];

        // Get matching RecipeIngredient
        foreach ($text3 as $data) {

            /**
             * @return RecipeIngredient()
             */
            $recipeIngredients = $recipeIngredientRepository->findBy([
                'name' => $data,
            ]);

            foreach ($recipeIngredients as $recipeIng) {
                $name = $recipeIng->getName();
                $recipeNames = $recipeRepository->findRecipeByKeywwords($name);

                foreach ($recipeNames as $recipeName) {
                    /**
                     * @return Recipe()
                     */
                    $recipies = $recipeRepository->findBy([
                        'id' => $recipeIng->getRecipe(),
                    ]);

                    // Built array with names & ids of recipies
                    foreach ($recipies as $key => $recipe) {
                        $recipeName = $recipe->getName();
                        $recipeId = $recipe->getId();
                        $recipiesArray[] = ['name' => $recipeName];
                        $recipiesArray[] = ['id' => $recipeId];
                    }
                }
            }
        }

        $response = new Response();
        $response->setContent(json_encode([
            'recipies' => $recipiesArray,
        ]));

        $response->headers->set('Content-Type', 'application/json');

        return $response;
    }

    return new Response(
        'Something wrong...',
        Response::HTTP_OK,
        ['content-type' => 'text/html']
    );
存储库:

  /**
     * @return Recipe[] Returns an array of Recipe objects
     */
    public function findRecipeByKeywwords($value)
    {
        return $this->createQueryBuilder('r')
            ->andWhere('r.name LIKE :val')
            ->setParameter('val', '%'.$value.'%')
            ->orderBy('r.id', 'ASC')
            ->setMaxResults(10)
            ->getQuery()
            ->getArrayResult();
    }

Symfony 2.1

$response = new Response(json_encode(array('recipies' => $recipiesArray)));
$response->headers->set('Content-Type', 'application/json');

return $response;
Symfony 2.2及更高版本

您有一个特殊的JsonResponse类,它将数组序列化为JSON:

use Symfony\Component\HttpFoundation\JsonResponse;

//
//

return new JsonResponse(array('recipies' => $recipiesArray));

Symfony 2.1

$response = new Response(json_encode(array('recipies' => $recipiesArray)));
$response->headers->set('Content-Type', 'application/json');

return $response;
Symfony 2.2及更高版本

您有一个特殊的JsonResponse类,它将数组序列化为JSON:

use Symfony\Component\HttpFoundation\JsonResponse;

//
//

return new JsonResponse(array('recipies' => $recipiesArray));

安装包后,只需将包添加到AppKernel.php文件中:

// in AppKernel::registerBundles()
$bundles = array(
    // ...
    new JMS\SerializerBundle\JMSSerializerBundle(),
    // ...
);
配置的序列化程序作为jms\ U序列化程序服务提供:

$serializer = $container->get('jms_serializer');
$json=$serializer->serialize(['recipies' => $recipiesArray], 'json');
return new JsonResponse($json,200);
安装包后,只需将包添加到AppKernel.php文件中:

// in AppKernel::registerBundles()
$bundles = array(
    // ...
    new JMS\SerializerBundle\JMSSerializerBundle(),
    // ...
);
配置的序列化程序作为jms\ U序列化程序服务提供:

$serializer = $container->get('jms_serializer');
$json=$serializer->serialize(['recipies' => $recipiesArray], 'json');
return new JsonResponse($json,200);

对现在您也可以这样做:返回$this->json([])(symfony 5),但结果是相同的。我已经尝试了所有可能的方法来编码到json。我认为问题出在别的地方。。但是在哪里???异步?我很困惑…您尝试过将序列化程序与JsonResponse结合起来吗?对现在您也可以这样做:返回$this->json([])(symfony 5),但结果是相同的。我已经尝试了所有可能的方法来编码到json。我认为问题出在别的地方。。但是在哪里???异步?我很困惑…您尝试过将序列化程序与JsonResponse结合起来吗?