如何在Javascript中读取JSON(服务器响应)?

前端之家收集整理的这篇文章主要介绍了如何在Javascript中读取JSON(服务器响应)?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在一个服务器上发送一些请求,它回复我:
{"COLUMNS":["REGISTRATION_DT","USERNAME","PASSWORD","FNAME","LNAME","EMAIL","MOBILE","FACEBOOK_ID"],"DATA":[["March,17 2012 16:18:00","someuser",somepass,"somename","somesur","someemail",sometel,"someid"]]}

我尝试了很多,但似乎没有为我工作!

var xml2 = this.responseData;
var xml3 = xml2.getElementsByTagName("data");
Ti.API.log(xml3.FNAME);

对于这个代码,我得到“null”.

任何帮助将不胜感激!

解决方法

如果你想使用JSON格式,你的问题是[…]中的数据也需要成对,并分组在{…}像 here.

例如,

{ 
      "sales": [ 
         { "firstname" : "John","lastname" : "Brown" },{ "firstname" : "Marc","lastname" : "Johnson" }
      ] // end of sales array
    }

所以你可能有:

{"COLUMNS": [ 
  {"REGISTRATION_DT" : "19901212","USERNAME" : "kudos","PASSWORD" : "tx91!#1",... },{"REGISTRATION_DT" : "19940709","USERNAME" : "jenny","PASSWORD" : "fxuf#2",{"REGISTRATION_DT" : "20070110","USERNAME" : "benji12","PASSWORD" : "rabbit19",... }
 ]
}

如果服务器正在向您发送一些您称为res的内容,那么您可以在Javascript中解析它:

var o=JSON.parse(res);

然后,您可以在列中循环遍历每个实例,如下所示:

for (var i=0;i<o.COLUMNS.length;i++)
{  
        var date = o.COLUMNS[i].REGISTRATION_DT; .... 
}
原文链接:https://www.f2er.com/js/153765.html

猜你在找的JavaScript相关文章