这是我的控制器方法:
public function sendjsonAction()
{
$message = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Message')
->findAll();
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('message' => new
JsonEncoder()));
$message = $serializer->serialize($message, 'json');
return new JsonResponse($message);
}
这是我的路由器:
acme_store_sendjson:
pattern: /sendjson/
defaults: { _controller: AcmeStoreBundle:Default:sendjson}
这是我去 /sendjson/ 时得到的:
"[{\u0022id\u0022:1,\u0022iam\u0022:1,\u0022youare\u0022:2,\u0022lat\u0022:50.8275853,\u0022lng\u0022:4.3809764,\u0022date\u0022:{\u0022lastErrors\u0022:{\u0022warning_count\u0022:0,\u0022warnings\u0022:[],\u0022error_count\u0022:0,\u0022errors\u0022:[]},\u0022timezone\u0022:{\u0022name\u0022:\u0022UTC\u0022,\u0022location\u0022:{\u0022country_code\u0022:\u0022??
(并且类似地继续)
我尝试使用以下内容进行 ajax 调用(使用 jQuery):
$.getJSON('/app_dev.php/sendjson', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
我得到一个
Uncaught TypeError: Cannot use 'in' operator to search for '1549' in [{"id":1,...
当我更改 Symfony2 的响应类型时,我得到一个列表
[对象] [对象] [对象] [对象] [对象] [对象] ...
我究竟做错了什么?我应该解析答案以将 \u0022 转换为 " 还是我的响应从一开始就有错误?
编辑
我还尝试将控制器更改为:
public function sendjsonAction()
{
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new GetSetMethodNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$message = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Message')
->findAll();
$serializer = $serializer->serialize($message, 'json');
return new Response($serializer);
}
这次我得到了 VALID JSON,(根据 Jsonlint)但标头不是 application/json ...(这是有道理的,因为我发送的是响应而不是 JsonResponse ...)(但这就是我试图避免的JsonResponse 似乎正在改变添加奇怪的字符)
[{"id":1,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"I saw you over there what's up!"},{"id":2,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"I saw you over there what's up!"},{"id":3,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"I saw you over there what's up!"},{"id":4,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"I saw you over there what's up!"},{"id":5,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"I saw you over there what's up!"},{"id":6,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"I saw you over there what's up!"}]