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



我完全被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();
}
composer require jms/serializer-bundle

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

// in AppKernel::registerBundles()
$bundles = array(
// ...
new JMSSerializerBundleJMSSerializerBundle(),
// ...
);

配置的序列化程序可用作jms_serializer服务:

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

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 SymfonyComponentHttpFoundationJsonResponse;
//
//
return new JsonResponse(array('recipies' => $recipiesArray));

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

最新更新