简体   繁体   English

在javascript中解析JSON响应

[英]Parsing JSON response in javascript

That's the essence of my problem: It is necessary to list all "file": 那就是我的问题的本质:有必要列出所有“文件”:

{
    "results": [{
        "fromuserid": "Anonymous",
        "touserid": "sd68Kbmc02",
        "file": "943easd709bfb2f6",
        "subject": "test",
        "message": "ddd",
        "createdAt": "2013-07-18T20:16:08.023Z",
        "updatedAt": "2013-07-18T20:16:08.023Z",
        "objectId": "bRDvHb4X4M"
    }, {
        "fromuserid": "Anonymous",
        "touserid": "sd68Kbmc02",
        "file": "ef763asd134a8125",
        "subject": "test",
        "message": "ddd",
        "createdAt": "2013-07-18T20:13:56.997Z",
        "updatedAt": "2013-07-18T20:13:56.997Z",
        "objectId": "GaLWnbSFtg"
    }, {
        "fromuserid": "Anonymous",
        "touserid": "sd68Kbmc02",
        "file": "5e7ae0sd5f1b48d0",
        "subject": "etesrtes",
        "message": "dfv fv f",
        "createdAt": "2013-07-18T16:09:20.403Z",
        "updatedAt": "2013-07-18T16:09:20.403Z",
        "objectId": "X83Qd7ctwi"
    }]
}

I use: 我用:

$.getJSON("http://domain.me/user/show_user/name/?callback=?", function(data) {
    $('#tile').html("<a href='http://domain.me/?img=" + data['results'][0]['file'] + "' target='_blank'><img src='http://domain.me/" + data['results'][0]['file'] + ".jpg'/></a>");
});

I get one line. 我得到一行。 You want to display all lines data['results'][0]['file'] . 您要显示所有行data ['results'] [0] ['file']

$.getJSON("http://domain.me/user/show_user/name/?callback=?",
    function(data) 
        {
          var results = [];
          $.each(data['results'], function(i, result) {
            results.push("<a href='http://domain.me/?img=" + result['file'] + "' target='_blank'><img src='http://domain.me/" + result['file'] + ".jpg'/></a>");
          });
          $('#tile').html(results.join(""));
        }
);

You have to parse and loop through the elements of your parsed JSON data, something you can easily do with Array.map() (it is supported in all browsers but IE<9): 您必须解析并循环遍历已解析的JSON数据的元素,您可以使用Array.map()轻松地完成Array.map()除IE <9外,所有浏览器均支持该功能):

$.getJSON("http://domain.me/user/show_user/name/?callback=?", function(data) {
    var html = data.results.map(function(item, index, array) {
        return array[index].file;
    });
    $('#tile').html(html.join(", "));
});

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

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