Symfony 5/请求-响应:使用Ajax获取数据



当我尝试在ajax中获取数据时,返回的对象是空的

我在js:中发送我想要获得的数据的id

function selectMessage(id) {

$.ajax({
url: '{{ path('back_translation_update') }}',
method: 'GET',
data: {id: id}
}).done(function (response) {
console.log(response)
})

}

$('.updateMessage').click(function (evt) {
evt.stopPropagation()
selectMessage($(this).data('id'))
})

在控制器中,我寻找要返回的数据:

/**
* @Route("/update", name="back_translation_update", methods="GET|POST")
*/
public function getById(Request $request): Response
{
if ($request->isXMLHttpRequest()) {

$id = $request->get('id');
//            dd($id);

$message = $this->translationService->getTranslationById($id);

//            return new JsonResponse(['data' => $message]);

$response = new Response();
$response->setContent(json_encode([
'data' => $message,
]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}

}

我使用服务是因为使用存储库时我收到一个错误:getById((必须是Symfony\Component\HttpFoundation\Response的实例

带有:

$repositoryMessage = $this->em->getRepository(TranslationMessage::class); 
$message = $repositoryMessage->findOneBy(['id' => $id]);

因此该服务将在数据库中查找:

public function getTranslationById($translation_id)
{
$query = $this->em->createQueryBuilder()
->from(TranslationMessage::class,'message')
->select('message')
->where('message.id = ?1')
->setParameter(1, $translation_id);

$message = $query->getQuery()->getResult();
//    dd($message);
return $message;
}

所有的dd((都给出了预期的值:

  • 进入getById((:查找的行的id

  • 进入getTranslationById((:所查找的对象

但在XHR中,数据包含一个空对象:uh:

与新的JsonResponse相同,在这里评论道

我错过了什么?帮助

使用Aurowire获取messageRepository对象并使用$this->json()返回JsonResponse

/**
* @Route("/update", name="back_translation_update", methods="GET|POST")
*/
public function getById(Request $request, TranslationMessageRepository $messageRepository): JsonResponse
{        
$id = $request->query->get('id');
$message = $messageRepository->find($id);
if(!$message) { return new NotFoundHttpException(); }
return $this->json([
'success' => true,
'data' => $message
]);

}

定义成功函数而不是完成函数

function selectMessage(id) {
$.ajax({
url: "{{ path('back_translation_update') }}",
method: 'GET',
data: { id: id }
success: function(data) {
console.log(data)
}
})

}

最新更新