我想打印一个JSON数据列表,其中一个键作为jquery中的列表头

时间:2016-11-07 14:48:35

标签: javascript jquery json

{
  "error": [{
      "domain": "(SA 1) ",
      "LessonName": "SA 1 Unit 1",
    }, {
      "domain": " (SA 1)",
      "LessonName": "SA 1 Unit 2",
    }, {
      "domain": " (SA 1) ",
      "LessonName": "SA 1 Unit 3",
    }, {
      "domain": "(SA 2) ",
      "LessonName": "SA 2 Unit 1",
    }, {
      "domain": "(SA 2) ",
      "LessonName": "SA 2 Unit 2",
    }, {
      "domain": "(SA 2) ",
      "LessonName": "SA 2 Unit 3",
    }, {
      "domain": "(PSLT) ",
      "LessonName": "PSLT 1",
    }, {
      "domain": "(PSIT) ",
      "LessonName": "PSIT 1",
    },

  ]
}

以上是我正在使用的JSON对象的结构。

我想在jquery中打印出一个看起来像这样的排序列表,任何人都可以帮助

> SA 1(domain)
>  SA 1 Unit 1(lessons under domain)
>  SA 1 Unit 2
>  SA 1 Unit 3
> SA 2(domain)
>  SA 2 Unit 1(lessons under domain)
>  SA 2 Unit 2
>  SA 2 Unit 3
> PSLT(domain)
>  PSIT 1(lessons under domain)

这是我在下面使用的代码。但它无法打印所有域标题

jQuery.ajax({
  url: elaurl,
  type: 'GET',
  error: function(jqXHR, text_status, strError) {
    alert("no connection");
  },
  timeout: 60000,
  success: function(response) {
    console.log(response.error.length);
    json = response;
    var temp = '';
    var i = 0;
    var j = 0;

    //  var data = "'<h4>'" + response.error[i].domain + "'<h4/>'";

    for (i = 0; i < response.error.length; i++) {

      if (response.error[i].domain != response.error[i + 1].domain) {

        var data = '<h4>' + response.error[i + 1].domain + '<h4/>';

        $('#domain').append(data);
        i++;
      }
    }
  }
});

3 个答案:

答案 0 :(得分:0)

你知道你总是打印出#34;课程&#34;列表中每个项目的元素,您只想打印出&#34;域&#34;如果元素与之前的元素不同,是吗?

您的AJAX响应函数可能与此类似:

success: function(response) {
   var $html = $('#domain');
   response.error.forEach(function(e, i) {
     // only print the domain if it's different than the previous error
     if (i===0 || e.domain !== response.error[i-1].domain) {
       $('<h4/>').text(e.domain).appendTo($html);
     }

     // always print the lesson
     $('<h5/>').text(e.lesson).appendTo($html);
   });
}

答案 1 :(得分:0)

有几个问题:

1)数据质量。您的JSON不一致 - 例如您的域SA 1实际上在样本中以3种不同的方式表示为“(SA 1)”,“(SA 1)”和“(SA 1)”。这将导致它们之间的任何字符串比较失败,因为它们永远不会相互匹配。

2)代码不太正确。你甚至都没有尝试打印课程名称,并且循环中存在一个逻辑错误,你无缘无故地增加i一个额外的时间,这意味着你错过了一些行。

以下是更正的数据和代码:

<强> JSON

{
  "error": [{
    "domain": "(SA 1)",
    "LessonName": "SA 1 Unit 1",
  }, {
    "domain": "(SA 1)",
    "LessonName": "SA 1 Unit 2",
  }, {
    "domain": "(SA 1)",
    "LessonName": "SA 1 Unit 3",
  }, {
    "domain": "(SA 2)",
    "LessonName": "SA 2 Unit 1",
  }, {
    "domain": "(SA 2)",
    "LessonName": "SA 2 Unit 2",
  }, {
    "domain": "(SA 2)",
    "LessonName": "SA 2 Unit 3",
  }, {
    "domain": "(PSLT)",
    "LessonName": "PSLT 1",
  }, {
    "domain": "(PSIT)",
    "LessonName": "PSIT 1",
  },
  ]
};

<强>代码

success: function(response) {
  var currentDomain = "";
  var data = "";

  for (i = 0; i < response.error.length; i++) 
  {

    if (response.error[i].domain != currentDomain) 
    {
      data += '<h4>' + response.error[i].domain + '<h4/>';
      currentDomain = response.error[i].domain;
    }
    data += "Lesson: " + response.error[i].LessonName + '<br/>';
  }
  $('#domain').append(data);
}

答案 2 :(得分:0)

希望这会有所帮助。在尝试将您的结构放入HTML列表之前,您需要将其正确分组,否则事情会变得非常毛茸茸并容易出错。

阅读并播放下面的代码。它输出一个数组,其中包含您需要的层次结构,然后创建HTML。

&#13;
&#13;
var response = {
    "error": [
        {
            "domain": "(SA 1) ",
            "LessonName": "SA 1 Unit 1",
        }, {
            "domain": " (SA 1)",
            "LessonName": "SA 1 Unit 2",
        }, {
            "domain": " (SA 1) ",
            "LessonName": "SA 1 Unit 3",
        }, {
            "domain": "(SA 2) ",
            "LessonName": "SA 2 Unit 1",
        }, {
            "domain": "(SA 2) ",
            "LessonName": "SA 2 Unit 2",
        }, {
            "domain": "(SA 2) ",
            "LessonName": "SA 2 Unit 3",
        }, {
            "domain": "(PSLT) ",
            "LessonName": "PSLT 1",
        }, {
            "domain": "(PSIT) ",
            "LessonName": "PSIT 1",
        },
    ]
};

function success(response) {
    var currentDomain = '';
    // First make your group headers
    var redux = response.error
    // Get the headers first
    .reduce(function(acc, errorObj) {
        var cleanDomain = errorObj.domain.replace(/^\s+|\s+$/gm, '');
        if (cleanDomain !== currentDomain) {
            acc.push({ domain: cleanDomain, children: [] });
            currentDomain = cleanDomain;
        }
        return acc;
    }, [])
    // For each header, add children
    .map(function (domainObj) {
        // From all errors get the corresponding ones for lesson name, and take the title only
        var firstLessonFound = false;
        domainObj.children = response.error.reduce(function (acc, item) {
            if (item.domain.replace(/^\s+|\s+$/gm, '') === domainObj.domain) {
                var string = item.LessonName;
                if (!firstLessonFound) {
                    string += ' (blah)';
                    firstLessonFound = true;
                }
                acc.push(string);
            }
            return acc;
        }, []);
        return domainObj;
    });

    console.log(redux)
    // Here you then iterate over redux and generate your HTML
}

success(response);
&#13;
&#13;
&#13;