从python到javascript获取json数据

get json data from python to javascript

本文关键字:json 数据 获取 javascript python      更新时间:2023-09-26

我正在尝试访问从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中收到一条消息,说"未定义"。但数据打印正确,我无法访问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?有人能指出我做错了什么吗?

您正在序列化一个包含对象的数组;在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,我认为您还必须设置dataType:"json"。