我正在使用这个控制器从我的数据库中获取数据,然后将它们作为有效的 JSON 数据发回,但我的 http 响应虽然有有效的 JSON,但它是 text/html 而不是 application/json,所以 getJSON 不起作用。(除非 getJSON 无论如何都应该工作?)
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);
}
这是我访问 json url 时得到的:
[{"id":1,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"我在那边看到你怎么了!"},{" id":2,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"我在那边看到你怎么了!"},{"id": 3,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"我在那边看到你怎么了!"},{"id":4," iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"我在那边看到你怎么了!"},{"id":5,"iam": 1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"我在那边看到你怎么了!"},{"id":6,"iam":1,"youare":2,"lat":50.8275853,"lng":4.3809764,"msgbody":"我看到你了那边怎么了!"}]
所以我有另一个页面,称为“showall”,其中包含以下 Javascript:
$.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');
});
该JS的结果是这个html:
<ul class="my-new-list">
<li id="0">[object Object]</li>
<li id="1">[object Object]</li>
<li id="2">[object Object]</li>
<li id="3">[object Object]</li>
<li id="4">[object Object]</li>
<li id="5">[object Object]</li>
</ul>
如果我尝试使用 json_encode,那么事情会变得更加混乱。这是我得到的答案:
"[{\"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!\"}]"
转义双引号...!我应该向 json_encode 添加一个选项,以便它不会转义这些双引号吗?