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

时间:2020-07-21 12:11:43

标签: javascript ajax symfony

我完全受制于Ajax请求。我正在尝试使用JSON编码数组将响应发送到Ajax。 Ajax收到状态200响应,但仅发送字符串;不是我的变量。 我想知道问题是否是由于异步引起的...当我用Postman进行测试时,我可以看到完整的响应,但是Js给了我:{“ recipies”:[]}。

感谢您的帮助。

Ajax:

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();
    }

2 个答案:

答案 0 :(得分:0)

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));

https://symfony.com/doc/current/components/http_foundation.html

答案 1 :(得分:0)

composer require jms/serializer-bundle

安装软件包后,只需将捆绑软件添加到AppKernel.php文件中即可:

// in AppKernel::registerBundles()
$bundles = array(
    // ...
    new JMS\SerializerBundle\JMSSerializerBundle(),
    // ...
);

已配置的序列化器可作为jms_serializer服务使用:

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