如何从Python返回2个json对象,我可以在Jquery中捕获(前端)

时间:2015-06-02 09:26:11

标签: jquery json django python-2.7

我的Python文件 - >

from datetime import datetime
from django.shortcuts import render
from django.http import HttpResponse
import json as simplejson
import random

def Detail(request):
    res1 = "[{\"index\":\"1\",\"status\":\"0\",\"name\":\"xyz1\"},{\"index\":\"2\",\"status\":\"1\",\"name\":\"xyz2\"},{\"index\":\"3\",\"status\":\"3\",\"name\":\"xyz3\"}]";
    res2 = "[{\"index\":\"1\",\"address\":\"1\",\"email\":\"a@a.com\",\"area\":\"xyz\"},{\"index\":\"2\",\"address\":\"2\",\"email\":\"a@a.com\",\"area\":\"xyz\"}]"
    res3 = "{\"office\":\"xyz\",\"dept\":\"xyz\",\"location\":\"xyz\",\"building\":\"xyz\",\"floor\":\"xyz\",\"emp\":\"xyz\"}"
    result = simplejson.dumps({'lsd':res1,'detail':res2,'office': res3})
    return HttpResponse(simplejson.dumps(result), content_type = "application/json")

我的JQuery文件位于:

function onCall(item) 
{
  alert(item.lsd.name);
  alert(item.detail.index);
  alert(item.office.dept);
}

所以我的问题是如何构建这一行: 我无法在前端提醒它。 它说“item.lsd”找不到,因为我想从后端吟唱json字符串并将其作为回复发送

result = simplejson.dumps({'lsd':res1,'detail':res2,'office': res3})
python中的

以便我可以在Frontend中提醒我,我不想更改此行

return HttpResponse(simplejson.dumps(result), content_type = "application/json")

1 个答案:

答案 0 :(得分:0)

你还没有说出问题所在。

但一个明显的问题是各种res变量已经是JSON字符串。因此,如果将它们添加到dict并将整个内容转储到JSON,那么这些值将被双重转义。

不要那样做。将这些变量定义为基本类型:

res1 = [{"index": "1", "status": "0", "name": "xyz1"},
        {"index": "2", "status": "1", "name": "xyz2"},
        {"index": "3", "status": "3", "name": "xyz3"}]

等等。

此外,您接着将result dict转储到JSON,然后在返回响应时再将其转储 。不要这样做:只做一次。