获取JSON对象然后将部分添加到HTML

时间:2015-10-03 23:11:14

标签: javascript jquery html json

我一直在努力让脚本为我的Github网站工作,我正在处理一个JSON文件,以便在有序列表中获取HTML数组。

我一直在使用的代码是:

$(document).ready(function() {
  $.getJSON("https://raw.githubusercontent.com/vvoid-inc/LillyPak-Starbound/gh-pages/mods/stable.json", function(data) {
    $.each(mods, function(i) {
      var tempUrl = "";
      var tempApproved = "";

      if (data.mods[i].Repo[0] == 0) {
        tempUrl = data.mods[i].Repo[1];
      } else if (data.mods[i].Repo[0] == 1) {
        tempUrl = "http://community.playstarbound.com/resources/" + data.mods[i].Repo[1] + "/";
      } else {
        tempUrl = data.mods[i].Repo[1];
      }

      if (data.mods[i].Approved == true) {
        tempApproved = "checked";
      } else {
        tempApproved = "";
      }

      $("#modsList").append("<li><a href='" + tempUrl + "'>" + data.mods[i].Title + "</a> - by " + data.mods[i].Author + "<ul><li>\t- <input type='checkbox' " + tempApproved + "/> Approved</li></ul></li>");
    });

    console.log(data);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol id="modsList"></ol>

那么我做错了什么因为什么都没有...

1 个答案:

答案 0 :(得分:0)

这应该有效:

$(document).ready(function() {
  $.getJSON("https://raw.githubusercontent.com/vvoid-inc/LillyPak-Starbound/gh-pages/mods/stable.json", function(data) {
    $.each(data.mods, function(i, m) {
      var tempUrl = "";
      var tempApproved = "";

      if (m.Repo[0] == 0) {
        tempUrl = m.Repo[1];
      } else if (m.Repo[0] == 1) {
        tempUrl = "http://community.playstarbound.com/resources/" + m.Repo[1] + "/";
      } else {
        tempUrl = m.Repo[1];
      }

      if (m.Approved == true) {
        tempApproved = "checked";
      } else {
        tempApproved = "";
      }

      $("#modsList").append("<li><a href='" + tempUrl + "'>" + m.Title + "</a> - by " + m.Author + "<ul style='list-style-type:none'><li>\t - <input type='checkbox' " + tempApproved + " disabled/> Approved</li></ul></li>");
    });

    console.log(data);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ol id="modsList"></ol>

而不是$.each(mods, function(i) {它应该是$.each(data.mods, function(i, m) {mods[i].应为m.

此外,JSON文件中存在格式错误,但现在已修复。这导致错误无法显示。