0

我正在使用这个控制器从我的数据库中获取数据,然后将它们作为有效的 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 添加一个选项,以便它不会转义这些双引号吗?

4

2 回答 2

2

如果您依赖Content-Type,请使用header()设置适当的:

header('Content-type: application/json');
于 2013-02-11T16:51:56.590 回答
1

改变:

items.push('<li id="' + key + '">' + val + '</li>');

到:

items.push('<li id="' + key + '">' + val.msgbody + '</li>');

使用时不需要设置 Content-type $.getJSON-- 它假定输出为 JSON。如果您使用更通用的方法,如$.get$.post或,则需要它$.ajax。它们都允许您指定一个dataType: 'json'选项来告诉它输出也是 JSON,但是如果您忽略该选项,它们会查看Content-type来决定如何解析它。

于 2013-02-11T17:17:58.593 回答