简体   繁体   English

解码来自Ajax Call的Json响应

[英]Decode Json Response from Ajax Call

I am getting a json response from python script via a ajax call on my html page, which I am running on localhost. 我通过我的html页面上的ajax调用从python脚本获得json响应,我在localhost上运行。 When I alert /display the response it is in proper ajax format but I don't know how to decode it. 当我提醒 /显示响应时,它处于正确的ajax格式,但我不知道如何解码它。 JSON parse display [object] [object] . JSON解析显示[对象] [对象] Any help? 有帮助吗? Thanks in advance. 提前致谢。

HTML: HTML:

function getData() {
    // Code doesn't even enter this function but when i remove the $.ajax part it enters the function
    alert("I AM HERE");

    $.ajax({
        type: "GET",
        datatype: 'json',
        url: "/cgi-bin/check.py",
        data: {
            action: 'muawia()',
        },
        success: function(data) {
            alert(data);
        },
        error: function(data) {
            alert(data.responseText);
        }
    });
};

Python: 蟒蛇:

#!/usr/bin/python

import cgi, cgitb 
from StringIO import StringIO
import json

class myclass:
    def __init__(self):
            self.data = []


    def muawia(self):
        content=json.loads('{"access": {"token": {"issued_at": "2013-04-18T14:40:23.299903", "expires": "2013-04-19T14:40:23Z", "id": "4c5ef01f52c7404fb5324c520d25d1fe", "tenant": {"description": "admin tenant", "enabled": true, "id": "51ad87714b86442d9a74537d6f890060", "name": "admin"}}, "serviceCatalog": [{"endpoints": [{"adminURL": "http://10.199.0.250:8774/v2/51ad87714b86442d9a74537d6f890060", "region": "RegionOne", "internalURL": "http://10.199.0.250:8774/v2/51ad87714b86442d9a74537d6f890060", "id": "9869f55f0de2490685676b6ec27f6097", "publicURL": "http://10.199.0.250:8774/v2/51ad87714b86442d9a74537d6f890060"}], "endpoints_links": [], "type": "compute", "name": "nova"}, {"endpoints": [{"adminURL": "http://10.199.0.250:8080", "region": "RegionOne", "internalURL": "http://10.199.0.250:8080", "id": "321601d827ba4bbbb6de1df69fd43a1c", "publicURL": "http://10.199.0.250:8080"}], "endpoints_links": [], "type": "s3", "name": "swift_s3"}, {"endpoints": [{"adminURL": "http://10.199.0.250:9292", "region": "RegionOne", "internalURL": "http://10.199.0.250:9292", "id": "cca7d7a24dbe45b6ae08da2c023b0d82", "publicURL": "http://10.199.0.250:9292"}], "endpoints_links": [], "type": "image", "name": "glance"}, {"endpoints": [{"adminURL": "http://10.199.0.250:8776/v1/51ad87714b86442d9a74537d6f890060", "region": "RegionOne", "internalURL": "http://10.199.0.250:8776/v1/51ad87714b86442d9a74537d6f890060", "id": "14773153229d4e7f80e47cf7b1dd2d15", "publicURL": "http://10.199.0.250:8776/v1/51ad87714b86442d9a74537d6f890060"}], "endpoints_links": [], "type": "volume", "name": "cinder"}, {"endpoints": [{"adminURL": "http://10.199.0.250:8773/services/Admin", "region": "RegionOne", "internalURL": "http://10.199.0.250:8773/services/Cloud", "id": "064df72a67f54dffa68c07b8fc400bdb", "publicURL": "http://10.199.0.250:8773/services/Cloud"}], "endpoints_links": [], "type": "ec2", "name": "nova_ec2"}, {"endpoints": [{"adminURL": "http://10.199.0.250:8080/", "region": "RegionOne", "internalURL": "http://10.199.0.250:8080/v1/AUTH_51ad87714b86442d9a74537d6f890060", "id": "194df182a8c043e48175a40fb615064e", "publicURL": "http://10.199.0.250:8080/v1/AUTH_51ad87714b86442d9a74537d6f890060"}], "endpoints_links": [], "type": "object-store", "name": "swift"}, {"endpoints": [{"adminURL": "http://10.199.0.250:35357/v2.0", "region": "RegionOne", "internalURL": "http://10.199.0.250:5000/v2.0", "id": "34db74b5f32f4121932725b1146a1701", "publicURL": "http://10.199.0.250:5000/v2.0"}], "endpoints_links": [], "type": "identity", "name": "keystone"}], "user": {"username": "admin", "roles_links": [], "id": "b5902682120742baa150945d8a37ff47", "roles": [{"name": "admin"}], "name": "admin"}, "metadata": {"is_admin": 0, "roles": ["9aa2eb385f4e4a8e80ad5002c212e76b"]}}}')
        data=json.dumps(content, indent=4, separators = (', ', ': '))
        print data
        return

print "Content-Type: text/html\n"
x = myclass()
x.muawia()

You should use 你应该用

console.log(data)

rather than alert(data). 而不是提醒(数据)。 Alert will only show you strings 警报只会显示字符串

alert() only outputs strings. alert()只输出字符串。 So generally it would be the same as: 所以一般来说它会是这样的:

data = data.toString();
alert(data);

Use console.log or console.dir in combination with JSON.parse to show the actual object that is returned from the JSON.parse. 将console.log或console.dir与JSON.parse结合使用,以显示从JSON.parse返回的实际对象。

// In your $.ajax success method
var someVar = JSON.parse(data);
console.log(someVar);

You can also set it to a global variable temporarily to debug it via the Firebug/Chrome DevTools console by typing its name. 您还可以临时将其设置为全局变量,以通过键入其名称通过Firebug / Chrome DevTools控制台对其进行调试。 For example: 例如:

// In your $.ajax success method
window.data = data;

And then type "data" in your console. 然后在控制台中输入“data”。

Please note that this is a bad practice to ship to production, global variables cannot be garbage collected by your browsers JavaScript engine and especially a global variable name as data has a high possibility of turning into a conflict with other global variables. 请注意,这是运送到生产的不良做法,全局变量不能被浏览器JavaScript引擎垃圾收集,尤其是全局变量名称,因为数据很可能与其他全局变量发生冲突。 If you still want to use a global for some reason then make sure you use a solid naming convention to prevent error. 如果由于某种原因仍希望使用全局,请确保使用可靠的命名约定来防止错误。

You can use $.parseJSON to format your data correctly. 您可以使用$ .parseJSON正确格式化数据。 You may also want to remove the extra comma at the end of your error response function. 您可能还希望在错误响应函数结束时删除额外的逗号。 It can cause syntax errors. 它可能导致语法错误。 Remove the comma from "action: 'muawia()'," as well. 从“action:'muawia()',”中删除逗号。

success: function(data){
    r = $.parseJSON(data)
    alert(r.responseText);
},
error: function(data){
    r = $.parseJSON(data)
    alert(r.responseText);
}

Hope this helps! 希望这可以帮助!

That's absolutely normal as JSON.parse(stringData) create s normal JavaScript object, so you get the [object Object] in the alert. 这是绝对正常的,因为JSON.parse(stringData)创建了普通的JavaScript对象,因此您可以在警报中获得[object Object] You have to access each object's property to get its value. 您必须访问每个对象的属性才能获取其值。 In your case var jsonObj = JSON.parse(data); alert(jsonObj.access.token.issued_at); 在你的情况下var jsonObj = JSON.parse(data); alert(jsonObj.access.token.issued_at); var jsonObj = JSON.parse(data); alert(jsonObj.access.token.issued_at);

will be for instance "2013-04-18T14:40:23.299903" 例如“2013-04-18T14:40:23.299903”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM