【问题标题】:Fetching data from JSON.parse array从 JSON.parse 数组中获取数据
【发布时间】:2012-02-26 03:17:45
【问题描述】:

我陷入了这个问题,我正在调用一个返回 json 响应的 webService。

现在我想从该响应中获取特定值,但在互联网上搜索并苦苦挣扎后无法修复它。

这是我的代码:

var xhr = Titanium.Network.createHTTPClient({

onload : function(e) {
     Ti.API.info("Received text: " + this.responseText);
     alert('success');
     },
 // function called when an error occurs, including a timeout
 onerror : function(e) {
     Ti.API.debug(e.error);
     alert('error');
 },
 timeout : 5000
});

var data = {"data":"system.connect"};
xhr.open("POST","http://mytesturl.net/services/json");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
xhr.send("method=system.connect");

响应是这样的:

{"#error":false,"#data":{"sessid":"c4likn6vg33hngbpmobisrsbpcjjmf39","user":{"uid":0,"hostname":"102.119.85.120","roles":{"1":"anonymous user"},"session":"","cache":0}},"#response_code":200}

从上述响应中,我想获取 sessid 值。 什么是正确的方法?

【问题讨论】:

    标签: javascript json titanium appcelerator


    【解决方案1】:

    以下内容可以在jsfiddle.net上查看和测试。

    // Given a string of JSON called responseText
    var responseText = '{"#error":false,"#data":{"sessid":"c4likn6vg33hngbpmobisrsbpcjjmf39","user":{"uid":0,"hostname":"102.119.85.120","roles":{"1":"anonymous user"},"session":"","cache":0}},"#response_code":200}';
    
    // You can parse it to an object using JSON.parse
    var responseObj = JSON.parse(responseText);
    
    // And then access the properties as with any object
    console.log(responseObj ["#data"]["sessid"]);
    

    【讨论】:

    • 问题是当我尝试像var myData=this.responseText 这样保存我的回复然后我记录它时,它显示为空。我不知道为什么它显示为空,但是当我像this.responseText 一样记录它时,它给了我确切的响应
    猜你喜欢
    • 2011-05-23
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多