【问题标题】:get json data from python to javascript从python获取json数据到javascript
【发布时间】:2013-07-31 06:59:01
【问题描述】:

我正在尝试访问从 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?有人可以指出我做错了什么吗?

【问题讨论】:

  • 您为什么希望这些对象中的任何一个都具有message 属性?另外,data 是字符串还是 JSON 对象?
  • 对不起,那是错误的。我现在更改了变量名

标签: javascript jquery python ajax json


【解决方案1】:

你正在序列化一个包含一个对象的数组;在 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

【讨论】:

  • 非常感谢。这行得通,猜我在那里犯了一个愚蠢的错误:)
【解决方案2】:

尝试使用 jquery 的 getJSON 函数。

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

另外,如果你想使用 ajax,我相信你也必须设置 dataType: "json"。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2013-01-10
    相关资源
    最近更新 更多