我是Symfony2和许多软件包的新手,但我正在研究原型REST API,我使用了FOSRestBundle,还使用了Symfony2生成的本机CRUD。但是,我发现虽然Symfony2 CRUD代码返回正确的JSON格式响应,但POST给了我一个错误,我正在寻找有关如何解决问题的解释和教程。查看实体的GET和POST代码,在这种情况下可以说地址:
/**
* Lists all Address entities.
*
* @Route("/", name="address")
* @Method("GET")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('MyWebServicesBundle:Address')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Creates a new Address entity.
*
* @Route("/", name="address_create")
* @Method("POST")
* @Template("MyWebServicesBundle:Address:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Address();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
// Inserted new code for deserialization
$entity->setUseruid($request->request->get("useruid"));
$entity->setCity($request->request->get("city"));
$entity->setLatitude($request->request->get("latitude"));
$entity->setLongitude($request->request->get("longitude"));
$serializer = JMS\Serializer\SerializerBuilder::create()->build();
$entity = $serializer->deserialize($request->request->all(), 'Name\BundleName\Entity\Address', 'json');
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('address_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
假设我使用AJAX向API发送请求,这里分别是我的GET和POST代码:
$.ajax({
dataType: "json",
type: "GET",
url: "/symfony/web/app_dev.php/address/",
success: function (responseText)
{
alert("Request was successful, data received: " + responseText);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
$.ajax({
dataType: "json",
type: "POST",
data: {"id":1,"useruid":"Nothing","type":"Office in Space","latitude":"74.3","longitude":"33.2","displayed":true,"public":true,"verified":true,"street":"Something","city":"Something","country":"Space","region":"North America","created":"2009-03-07T00:00:00-0500","delete_status":"active"},
url: "/symfony/web/app_dev.php/address/",
success: function (responseText)
{
console.log("Request was successful, data received: " + JSON.stringify(responseText));
},
error: function (error) {
alert(JSON.stringify(error));
}
});
当GET返回正确时,POST返回以下错误:{“code”:500,“message”:“警告:json_encode():在/ var / www / projects / symfony / vendor / jms / serializer中检测到递归/src/JMS/Serializer/JsonSerializationVisitor.php第29行“}。我需要做什么来解决错误?我可以返回单个实体或所有实体,但POST只是将数据发送到创建实体的路径,从而产生错误。我已将我的JMSSerializer软件包从0.12。*更新为dev-master,并检查以确保AJAX发送的数据中没有NULL值,但错误仍然存在。如何让我的POST控制器从POST中发送给它的有效JSON创建数据?
我也试过PUT,结果是一样的,它没有更新资源,不应该只更新表中的记录吗?如果我需要提供更多信息以找出此错误的来源,请告诉我们! 代码已在上面进行了编辑。
答案 0 :(得分:0)
$ this-> redirect返回不是您想要的RedirectResponse对象。如果您想要返回重定向网址,只需返回array('redirect_url' => $this->generate(...))
,然后使用javascript重定向客户端。