json响应与不同对象的数组

时间:2015-03-09 22:33:52

标签: jquery arrays ajax json

我想发送一个包含2个不同对象数组的ajax调用的响应。 当我设置

 dataType: "json", 

ajax调用失败所以我认为控制器发送的格式是错误的。

$serializer = $this->container->get('jms_serializer');
        $json2 = $serializer->serialize($readyproblems, 'json', SerializationContext::create()->enableMaxDepthChecks());
        $json1 = $serializer->serialize($result, 'json', SerializationContext::create()->enableMaxDepthChecks());
        $json = '{"data1": ' . $json1 . '"data2":' . $json2 . '}';
        return new Response($json);

这将返回

{"data1": [{"id":4,"Description":"solution 4"},{"id":1,"Description":"sol 1"}]"data2":[{"id":1,"Description":"problima1"},{"id":2,"Description":"problima2"}]}

在ajax成功的时候我想获得像

这样的数据
function callback(data) {
data.data1[0].property
data.data2[1].property 
}
由于字符串不正确,

JSON.parse(data);也会导致错误

1 个答案:

答案 0 :(得分:0)

您在“data2”之前缺少逗号

{
    "data1": [
        {
            "id": 4,
            "Description": "solution 4"
        },
        {
            "id": 1,
            "Description": "sol 1"
        }
    ], "data2": [ // Comma added here
        {
            "id": 1,
            "Description": "problima1"
        },
        {
            "id": 2,
            "Description": "problima2"
        }
    ]
}

以下是如何修复您的代码

$serializer = $this->container->get('jms_serializer');
$json2 = $serializer->serialize($readyproblems, 'json', SerializationContext::create()->enableMaxDepthChecks());
$json1 = $serializer->serialize($result, 'json', SerializationContext::create()->enableMaxDepthChecks());
$json = '{"data1": ' . $json1 . ',"data2":' . $json2 . '}';
return new Response($json);