从python到javascrip获取json数据

2024-10-16 20:47:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图访问从python脚本发送的json数据。在python脚本中,我以以下格式向Ajax成功函数发送数据:

def main():
"""Create instance of FieldStorage""" 
dat = cgi.FieldStorage( keep_blank_values = True ) 

Start_date = "07/01/2013"
dc = ['las','sjc']
sys = "All"



result = [{"startdate":Start_date,"datacenter":dc,"system":sys}]

res = json.dumps(result)

print res

现在在javascript中,我试图访问Json的各个值,但是在console.log中收到一条消息,上面写着“undefined”。但是数据打印正确,我无法访问JSON的各个对象。

             $.ajax({
                    type: 'get',
                    url: '/cgi-bin/worlddata.py',
                    data: $(form).serialize(),


                    success: function(data, status) {


                      var response = JSON.parse(data);
                      console.log("THe json is "+response.datacenter); //prints undefined
                      console.log("result is "+data); // prints result is [{"startdate": "07/01/2013", "system": "All", "datacenter": ["las", "sjc"]}]

                      console.log("The status is "+status); // prints The status is success
                      console.log(data.datacenter); // prints undefined

我的问题是如何访问response.message或data.message?有人能指出我做错了什么吗?


Tags: 数据脚本logjsondataisresponsestatus
2条回答

您正在序列化包含对象的数组;在python端,[]是多余的。删除它们,然后在javascript中,您可以访问result.system、result.startdate和result.datacenter等值

result = {"startdate": Start_date,"datacenter": dc,"system": sys}
print json.dumps(result)

然后

var response = JSON.parse(data);
console.log("The json startdate is " + response.startdate); //prints undefined

尝试使用jquery的getJSON函数。

$.getJSON('/cgi-bin/worlddata.py', {
    $(form).serialize()
}).success(data, status) {
   success stuff goes here
});

另外,如果您想使用ajax,我相信您还必须设置数据类型:“json”。

相关问题 更多 >