我想从JSON数据中打印出一个列表,在jquery中以键作为列表头


{
  "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++;
      }
    }
  }
});

你知道你总是要打印出列表中每个项目的"lesson"元素,而你只希望打印出"domain"元素,如果它与它之前的一个不同,对吗?

您的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)数据质量。你的JSON是不一致的-例如,你的域sa1实际上在你的样本中以3种不同的方式表示,如"(sa1)"。、"(sa1)"及"(sa1)"。这将导致它们之间的任何字符串比较失败,因为它们永远不会相互匹配。

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);
}

希望这对您有所帮助。在尝试将您的结构放入HTML列表之前,您需要对其进行适当的分组,否则事情会变得非常复杂并且容易出错。

阅读并使用下面的代码。它输出一个数组,其中包含了创建HTML所需的层次结构。

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);

最新更新